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
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.
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(\).
Inside double quotes, single quotes are normal characters and vice versa. Otherwise you can escape them by prepending a backslash: "\"" or '\'' .
You are allowed to use both. In JavaScript there is no difference between both (while e.g. in PHP there is a difference).
Use backslash
"Workers\'_Compensation";
Inside a selector you would require 2 of them "Workers\\'_Compensation";
Check Fiddle
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