Jeff Lamb Jeff Lamb - 1 year ago 88
Javascript Question

Escape characters in jQuery variables not working

I'm having issues with escaping characters (namely period) found in variables when using selectors in jQuery. I was going to type this all out, but it was just easier taking a screenshot of my console window in Chrome.

Chrome Console Screenshot

It looks like the variables and the clear text versions match up. I expect

to return the div, just like
returns a div. It does not. Why?

Answer Source

You have to think in terms of the individual parsers that will be examining your string values. The very first one, of course, is the JavaScript parser itself. Backslash characters have a meaning in the string grammar, so if you want a single backslash in a string it needs to be doubled.

After the string is parsed from the source code into an internal string value, the next thing that'll pay attention to its contents (in this case) is the CSS selector evaluator (either Sizzle or the native querySelector code; not sure which in the case of strings with escapes like this). That code only needs one backslash to quote the . in order that it not be interpreted as introducing a class name match.

Thus, escName = "jeffrey\\.lamb"; is all you need in this case.