Moss
Moss

Reputation: 3803

Trying to escape a string to use as a jQuery selector

I have the following code, which I stole from another SO question,

$('#'+'^`test'.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\\\$&"))

which produces the following error.

Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)

I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on. I don't get why that error is happening, because if I manually add the slashes into the string like,

$('#'+'\\^\\`test')

then it works fine. What's wrong with the regex method?

Upvotes: 2

Views: 76

Answers (4)

ced E.
ced E.

Reputation: 1

You need 2 times the escape . Becouse first the replace/regex need the escape to write a escape. The next escape is need from jquery by $().

More clear syntax as the postet regex is:

"#^bla`".replace('^','\\\^').replace('`','\\\`');

will replace "#^bla`" to "#\\^bla\\`".

Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)

If you want to use your regex you must also escape [ ] with \[ and \].

"+".replace(/[!"#$%&'()*+,.'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, "yes")

Upvotes: 0

Maciej Kozieja
Maciej Kozieja

Reputation: 1865

How about using this?

const $ID = function(selector){
    return $('[id="' + selector.match(/#?(\S+)/)[1] + '"]')
}

Then you can use it just like jquery

$ID('#^`div')

Upvotes: 0

Me.Name
Me.Name

Reputation: 12534

Another work around is to use the vanilla getElementById, which doesn't parse the selector. That way you still have the efficiency of selecting by id:

let res = $(document.getElementById('^`test'));

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074028

I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on.

By far the simplest way to address that is with an attribute selector:

$('[id="' + theId + '"]').doSomething();

As long as theId doesn't contain backslashes or double quotes, no need for further escaping.

Upvotes: 3

Related Questions