7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kishore
  • 413
  • 1
  • 4
  • 20
  • 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.) – Jukka K. Korpela Jun 30 '14 at 09:44
  • 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 https://www.youtube.com/watch?v=4dr3y0ZT3vI – InfiniteStack Sep 28 '21 at 20:12

2 Answers2

28

You will need to use regular expression for this,

st.replace(/"/g, '\\"');

Check out more on regular expressions here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vasa
  • 787
  • 8
  • 21
0

Try this:

str.replace(/["']/g, "")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DWX
  • 2,282
  • 1
  • 14
  • 15
  • 6
    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 ;-) – Erenor Paz Sep 27 '16 at 08:52