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.

Share:
26,695
kishore
Author by

kishore

I am a Python Developer.

Updated on July 16, 2022

Comments

  • kishore
    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
      Jukka K. Korpela almost 10 years
      It 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
      InfiniteStack over 2 years
      Nowadays 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
    karim_fci almost 9 years
    Here is one mistake. not st.replace(). It should be str.replace().
  • vasa
    vasa almost 9 years
    the variable used in the qn is 'st'. Hence, st.replace()
  • Erenor Paz
    Erenor Paz over 7 years
    This 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
    blue-sky about 7 years
    @vasa minor point, this does not update 'st' in place, should use st = st.replace(/"/g, '\\"');
  • vasa
    vasa about 7 years
    @blue-sky Agree, strings are immutable in JS.
  • Wes Modes
    Wes Modes about 3 years
    This does not replace single quotes.