petko_stankoski
petko_stankoski

Reputation: 10713

Escaping parenthesis in jquery contains

Here's what I have:

item.find('div:contains(' + name + ')')

However, in some cases, name contains parenthesis. In one case, name has this value:

"brown (ok xl (1))"

And item.find('div:contains(' + name + ')') doesn't work. The parenthesis are the problem. How to escape them?

Upvotes: 0

Views: 2648

Answers (4)

Daniel Kaplan
Daniel Kaplan

Reputation: 67360

You don't have to implement your own solution for this (anymore?). Use jQuery.escapeSelector():

console.log($.escapeSelector('this selector\'s got (many) special chars!@#$#@#$.***'));
// this\ selector\'s\ got\ \(many\)\ special\ chars\!\@\#\$\#\@\#\$\.\*\*\*

$($.escapeSelector('this selector\'s got (many) special chars!@#$#@#$.***'))
// { "length": 0, "prevObject": { /* ... */ } }


$('this selector\'s got (many) special chars!@#$#@#$.***')
// Uncaught Error: Syntax error, unrecognized expression: this selector's got (many) special chars!@#$#@#$.***

Upvotes: 0

Harish Ambady
Harish Ambady

Reputation: 13121

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^'{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\ For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

Here is a function to escape special characters and return a valid jQuery selector. Pass your string to this function before use:

function jqSelector(str)
{
    return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}

Upvotes: 4

codefreak
codefreak

Reputation: 7131

I had same problem few days ago, but for some weird reason @Zeta's solution didn't work for me so I came up with

name = name.replace(/(\(|\)).*/g,"");
item.find("div:contains(" + name +")");

It isn't perfect but it works :)

EDIT

A better RegEX:

name = "(d)test thingie(assaf)(asdads".replace(/\(([^\)])*\)/g,"$1 ").replace(/\(|\)(.)*/g,"$1 ");

If you want to eliminate everything in between parenthesis so that contains work you can use:

name = "(d)test thingie(assaf)(asdads".replace(/\(([^\)])*\)/g,"").replace(/\(|\)(.)*/g,"");

Upvotes: 1

Zeta
Zeta

Reputation: 105886

As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. (source)

So simply use

item.find('div:contains(\'' + name + '\')')
/* or */
item.find('div:contains("' + name + '")')

Note that you need to escape additional quotation marks inside name if you have any.

Upvotes: 0

Related Questions