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?
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', '.
We can use a backslash to escape characters that have special meaning in regular expressions (e.g. \ will match an open bracket character).
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With