[javascript] 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.

This question is related to javascript string escaping

The answer is


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.


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to escaping

Uses for the '"' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?