How to escape all single and double quotes in JavaScript
26,695
You will need to use regular expression for this,
st.replace(/"/g, '\\"');
Check out more on regular expressions here.
Comments
-
kishore almost 2 years
I have a variable in my script,
var st = ""
In that quotes I have to give a string and this string contains lot of single and double quotations.
I think there isn't any problem with single quotations, but a problem with the double quotes (") only.
In this I can't manually replace
\"
for all, even I tried with an editor that"
replace with\"
, but it's not working.-
Jukka K. Korpela almost 10 yearsIt is unclear what is asked here. Escaping
"
as\"
within a string literal with"
as delimiters is sufficient. If it does not work, you should ask a specific question with an example that actually demonstrates the issue. (“Not working” is not a description of what happens.) -
InfiniteStack over 2 yearsNowadays it's Backtick Quotes (at the time op asked the question backticks weren't part of JavaScript spec yet) Here's how it works youtube.com/watch?v=4dr3y0ZT3vI
-
-
karim_fci almost 9 yearsHere is one mistake. not st.replace(). It should be str.replace().
-
vasa almost 9 yearsthe variable used in the qn is 'st'. Hence, st.replace()
-
Erenor Paz over 7 yearsThis does not escape, it only removes all the quotes. This is not really what the OP was asking...but since you're doing the replace on the variable
str
, there's no fear about modifying original string ;-) -
blue-sky about 7 years@vasa minor point, this does not update 'st' in place, should use st = st.replace(/"/g, '\\"');
-
vasa about 7 years@blue-sky Agree, strings are immutable in JS.
-
Wes Modes about 3 yearsThis does not replace single quotes.