tags:

views:

717

answers:

3

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?

+3  A: 

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().

eyelidlessness
Nice solution +1
redsquare
Thanks, I was able to use this.
tessa
A: 

I don't use jQuery much, but the problem with your first one is that you're trying to put in text where it should be a selector - then you tried using a selector ":contains", but you then tried to escape the "(". Have you tried $("#fscaTotals td").filter(":contains('(')")? Use contains, but don't try to escape the parentheses.

Russell Leggett
Syntax error, unrecognized expression: '(')
eyelidlessness
+3  A: 

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]*\)')")

BTW, i tested the regex example above with RegexBuddy and I think it is correct for your needs.

Jon Erickson
+1. This is a nice alternative solution to mine, but I would say that it's basically a syntactic sugar around mine.
eyelidlessness
This is interesting, saving for later. :)
tessa
@eyelidlessness definately, both have the same outcome, but differing implementations. If he is looking to reuse functionality I would recommend implementing the regex filter, but if this is a one off then you solution works 100% just fine, it is probably good to display both so people who find this question by way of search later on can view the alternatives. =)
Jon Erickson