Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 851
Samik Sengupta Avatar asked Jul 17 '12 05:07

Samik Sengupta


1 Answers

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.

like image 178
Willem D'Haeseleer Avatar answered Oct 04 '22 09:10

Willem D'Haeseleer