47

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samik Sengupta
  • 1,944
  • 9
  • 31
  • 51

4 Answers4

78

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
  • Why is a regular expression needed for replacing literal strings? – Peter Mortensen Jul 19 '20 at 17:59
  • @PeterMortensen it could be necessary for example when working with GraphQL whose scalars generally only include ID, String, Int, Float, Boolean, so no Maps etc. Using this method it's easy to save objects as strings which can be useful in certain situations. without the regex, the JSON will be escaped and the queries will fail. – Christoffer Oct 16 '20 at 08:49
  • This fixed the issue. Thanks – Bishal Paudel Jan 19 '22 at 02:16
  • I've run into a double quote issue with the Apollo client for GraphQL and the above code doesn't work in that situation. – Wayne Smallman Apr 18 '23 at 13:07
  • @WayneSmallman do you want to post a stack overflow question with some more details ? Feel free to link it here – Willem D'Haeseleer Apr 18 '23 at 15:47
  • Hi @WillemD'Haeseleer, it turned out I had the code to hand elsewhere in the application: `JSON.stringify(string).replace(/"(\w+)"\s*:/g, '$1:')` – Wayne Smallman Apr 18 '23 at 19:43
8

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)

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 JavaScript 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 JavaScript. You'd do any SQL-related escaping server-side.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 1
    this will not work as it will only relace the first double quote – Willem D'Haeseleer Jul 17 '12 at 06:03
  • @nnnnnn Thanks for the additional info on SQL query escaping. For the test project I was working on, I decided to escape any must-escape characters before I send them as a string in a query to the server. – Samik Sengupta Jul 17 '12 at 06:27
  • You're not sending SQL queries from JS to the server are you? That would be a major security problem. (Also, I've never used MySQL, but the databases I do use like SQLServer, DB2 and Oracle don't need to escape double-quotes, and don't escape singles with backslashes...) – nnnnnn Jul 17 '12 at 06:35
6

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.

derekmc
  • 161
  • 1
  • 7
0
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
loler
  • 2,594
  • 1
  • 20
  • 30