views:

68

answers:

2

Hello world,

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

+4  A: 

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?

Justin Ethier
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) });
A: 

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);
});
Guffa