Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you escape parentheses in jQuery selector?

Tags:

jquery

I am trying to check if a td innertext contains parentheses (). The reason is I display negative numbers as (1000) and I need to convert them to -1000 to do math. I've tried a couple different ways but can't seem to get it right. I know there are non-jQuery ways to do this but at this point it's just bugging me.

$(tdElement[i]).find("\\(").length > 0 

This doesn't throw error, but it doesn't find an innertext of (1000):

$(tdElement[i]).find("\\(")
{...}
    context: {object}
    jquery: "1.3.1"
    length: 0
    prevObject: {...}
    selector: "\("

Another method I tried was:

$("#fscaTotals td").filter(":contains('\\(')")

This throws error "Exception thrown and not caught". It seems to work for other characters though. Example: . , ; < >

So, how do you escape parentheses in jQuery?

like image 747
tessa Avatar asked Jul 20 '09 18:07

tessa


People also ask

How to escape a special character in jQuery?

The escapeSelector() method in jQuery is used to escape CSS selectors which have special significant character or string. It can select the element of id('#ID1', '#ID2') and elements of class('. class1', '.

How do you escape a square bracket?

We can use a backslash to escape characters that have special meaning in regular expressions (e.g. \ will match an open bracket character).


2 Answers

I think you'll have to use a filter function like:

$('#fscaTotals td *').filter(function(i, el) {
    return !!$(el).text().match(/\(/);
});

Edit: I think this is a bug in jQuery's :contains().

like image 147
eyelidlessness Avatar answered Sep 24 '22 02:09

eyelidlessness


You can add a RegEx filter

This technique is explained in this Blog Entry

$.extend($.expr[':'], {  
    regex: function(a, i, m, r) {  
        var r = new RegExp(m[3], 'i');  
        return r.test(jQuery(a).text());  
    }  
});

Then you could use a regular expression like so.

("#fscaTotals td:regex('\([0-9]*\)')")

By the way, I tested the RegEx example above with RegexBuddy and I think it is correct for your needs.

like image 41
Jon Erickson Avatar answered Sep 26 '22 02:09

Jon Erickson