0

EDIT: I would like to avoid doing something like this:

var str = 'Hello'; 
if ( str == 'Hello') { 
    alert(str); 
} 

I would rather do:

var str = 'Hello'; 
$(str).filter(':contains("Hello")').each(function(){ 
    alert(this) 
});

I've tried a lot of things:

$(str).text().method1().method2().method3();
$(str).val().method1().method2().method3();
$(str).contents().method1().method2().method3();

Nothing worked. Is it possible to do this?

Thank you for your time.

Kind regards,
Marius

1
  • You might want to try and explain your motivation. It isn't currently clear why you would want want to use jQuery for something it wasn't designed for, instead of using the simple javascript snippet. Commented May 12, 2010 at 13:08

2 Answers 2

4

jQuery selectors don't work like that. The whole idea is that they select elements of the Document Object Model (DOM). In other words, tags in your HTML document (page).

If you want to use a string variable, you can just access it directly as str. No jQuery is even required.

That said, is there a specific jQuery method (or methods) that you wanted to use to manipulate a string?

Sign up to request clarification or add additional context in comments.

1 Comment

I want to avoid doing this: var str = Hello; if ( str == 'Hello') { alert(str); } I would rather do: $(str).filter('contains("Hello")').each(function(){ alert(this) });
0

Put the value in an array, they you can use the grep method to filter out the items in the array that matches a criteria:

$($.grep([str], function(e){
  return e == 'Hello';
})).each(function(){
  alert(this);
});

You can also make a plugin to make it more like the code that you wished for:

(function($){
  $.fn.eq = function(str) {
    return $($.grep(this, function(e){ return e == str; }));
  };
})(jQuery);

Usage:

var str = 'Hello';
$([str]).eq('Hello').each(function(){
  alert(this);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.