Reputation: 163
i have a little problem with .search
this is the code
// filter - posts
jQuery('.filter_by').live('click',function(){
var target_fi = jQuery(this);
var target_cat = target_fi.parents('.cat').children('.namechanger').val();
target_fi.next().fadeIn(100);
var cat_all = target_fi.prev().find("option").each(function(i){
if(jQuery(this).attr('data-cats').search(target_cat) == -1){
jQuery(this).css({"display":"none"});
}
});
});
I want to use the variable target_cat
with .search
I can't do this .search(/target_cat/)
Upvotes: 1
Views: 388
Reputation: 13557
To convert anything into a regular expression, simply drop it into the constructor:
var something = "foobar"; var expression = new RegExp(something, 'i');
note the second argument for flags. See RegExp for more info on the constructor and Regular Expressions for details on how things work.
If your something
contains "special characters" (such as |
, ?
, {
) you need to escape them, if you want them to be meant literally (/foo?/
vs. /foo\?/
). Here's a function that'll esacpe all relevant characters for you:
function escapeRegEx(string) {
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
jQuery.live
, but should use jQuery.on
instead.search()
when .match()
sufficesjQuery(this).css({"display":"none"});
when jQuery(this).hide();
sufficesjQuery(this)
in your loop - one should be enough - variables are your friends.Upvotes: 1
Reputation: 1038
You need to create RegExp
object and pass that to search
method
if(jQuery(this).attr('data-cats').search(new RegExp(target_cat)) == -1 )){
...
}
Upvotes: 1
Reputation: 9211
If you want to make a regular expression out of the string value of target_cat
, then you can do this:
var mySearchTerm = new RegExp(target_cat);
...
if(jQuery(this).attr('data-cats').search(mySearchTerm) == -1){
Upvotes: 1