Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape all single and double quotes in JavaScript [duplicate]

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.

like image 514
kishore Avatar asked Jun 30 '14 07:06

kishore


People also ask

How do you escape all quotes in JavaScript?

To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!

How do you replace a quote in JavaScript?

Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.

Are single and double quotes the same JavaScript?

In JavaScript, single (' ') and double (“ ”) quotes are frequently used for creating a string literal. Generally, there is no difference between using double or single quotes, as both of them represent a string in the end.


1 Answers

You will need to use regular expression for this,

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

Check out more on regular expressions here.

like image 170
vasa Avatar answered Sep 20 '22 05:09

vasa