Escaping Strings in JavaScript
Solution 1
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
Solution 2
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
Solution 3
A variation of the function provided by Paolo Bergantino that works directly on String:
String.prototype.addSlashes = function()
{
//no need to do (str+'') anymore because 'this' can only be a string
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
By adding the code above in your library you will be able to do:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
EDIT:
Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
Solution 4
Use encodeURI()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.
Steve Harrison
Updated on July 05, 2022Comments
-
Steve Harrison almost 2 years
Does JavaScript have a built-in function like PHP's
addslashes
(oraddcslashes
) function to add backslashes to characters that need escaping in a string?For example, this:
This is a demo string with 'single-quotes' and "double-quotes".
...would become:
This is a demo string with \'single-quotes\' and \"double-quotes\".
-
Rick Copeland about 15 yearsSo then the answer is "no, there is no built-in function like PHP's addslashes"
-
Steve Harrison about 15 yearsGood, I'll add this function to my [ever growing] collection of functions/methods that are missing from JavaScript... Thanks!
-
Benjamin Gruenbaum about 11 yearsWorth noting that extending native javascript objects is considered by many bad practice.
-
Marco Demaio about 11 years@BenjaminGruenbaum: if you are afraid of conflicts you can add
if(!String.prototype.addSlasches)
before extending -
B T over 10 yearsExactly how does that help? If you're expecting one addSlashes function and you get another one, you're likely gonna end up with a really hard to find bug. Better to throw an exception if there's a conflict
-
Marco Demaio over 10 years@BT: well an
addSlashes
func is actually supposed to add slashes in one way or another. Anyway i updated the code in the answer to reflect your suggestion. -
Tom Pažourek about 10 yearsCould you please explain the '\u0000' replace? Thank you.
-
user almost 10 yearsThis is an excellent answer. I'm surprised there's no 'obvious' built in method to escape quotes but this does the job. Are there any caveats?
-
dlaliberte about 9 yearsThe result of JSON.stringify() with a string is a string with double quotes around your string. It is the string that, when evaluated, will result in the same string you started with. So JSON.stringify('my string with "quotes"') returns the string: "my string with \"quotes\"", which you might enter in JavaScript as '"my string with \"quotes\""'.
-
gengkev over 8 yearsOne downside is that things like
\x00
aren't supported, and are instead represented with the lengthier\u0000
. -
Hashbrown almost 8 yearsThis catches newlines, tabs, et cetera too, which the other answers ignored. And without it turning into a list of all possible special characters taboot. This is the best answer. Worth noting that it only escapes
"
and not'
, though. -
stevendesu over 7 yearsBeautiful, elegant, efficient. Used this to debug some parsers I was writing - amazingly useful
-
sleske about 7 years@Hashbrown: Yes, that's true. That is because it creates JSON strings, and JSON strings are always delimited by double quotes (
"
) according to spec. In JavaScript,'
is a valid string delimiter, too, but not in JSON. -
N-ate over 6 years\u0000 is a null character. I'm not certain why it is necessary to remove.
-
NGloom over 3 yearsreally rocks, bro !
-
Israel Obanijesu over 3 yearshow can we check if the string contains a slash before adding a new one
-
Israel Obanijesu about 3 yearsThis sucks in a node environment
-
Mario over 2 yearscareful with using
escape()
, it is in Annex B, which means not deprecated but undesired side-effects. Read more at MDN -
traxium almost 2 years@gengkev
\u0000
could be replaced with\x00
byJSON.stringify(str).replaceAll(/\\u00([\da-f]{2})/g, '\\x$1')