Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a single quote in jQuery? [duplicate]

I am trying to use the escape function to escape a single quote:

var tagDesc = "Workers'_Compensation";
tagDesc = escape(tagDesc);
$("#" + tagDesc + ".tag").css("display", "none");

The escape function replaces the single quote with %27 to "Workers%27_Compensation".

So I get an error,

Microsoft JScript runtime error: Syntax error, unrecognized expression: #Workers%27_Compensation.tag

like image 383
skwrox Avatar asked May 30 '13 21:05

skwrox


People also ask

How do I bypass a single quote in JavaScript?

We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

How do you escape a single quote from a string?

You need to escape a single quote when the literal is enclosed in a single code using the backslash(\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\).

How do you escape a single quote in JQ?

Inside double quotes, single quotes are normal characters and vice versa. Otherwise you can escape them by prepending a backslash: "\"" or '\'' .

Does jquery require double quotes?

You are allowed to use both. In JavaScript there is no difference between both (while e.g. in PHP there is a difference).


1 Answers

Use backslash

"Workers\'_Compensation";

Inside a selector you would require 2 of them "Workers\\'_Compensation";

Check Fiddle

like image 52
Sushanth -- Avatar answered Nov 03 '22 04:11

Sushanth --