javascriptstringescaping

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?


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.


Solution

  • 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 in Using Regular Expressions with JavaScript.