How do I replace a double-quote with an escape-cha

2019-02-04 01:31发布

问题:

Say I have a string variable (var str) as follows-

Dude, he totally said that "You Rock!"

Now If I'm to make it look like as follows-

Dude, he totally said that \"You Rock!\"

How do I accomplish this using the JavaScript replace() function?

str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.

Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform? Quotes and Commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.

回答1:

You need to use a global regular expression for this, try it this way

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

check out regex syntax and options for the replace function here:

http://www.regular-expressions.info/javascript.html



回答2:

Try this:

str.replace("\"","\\\""); // (escape backslashes and embedded double-quotes)

Or, use single-quotes to quote your search and replace strings:

str.replace('"','\\"');   // (still need to escape the backslash)

UPDATE: As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally you have to pass a regex with the g (global) flag:

str.replace(/"/g,"\\\"");
// or
str.replace(/"/g,'\\"');

But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:

var str = "Dude, he totally said that \"You Rock!\"";

But this is necessary only in a string literal. That is, if your JS variable is set to a value that a user typed in a form field you don't need to this escaping.

Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JS. You'd do any SQL-related escaping server-side.



回答3:

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.



回答4:

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);