Escaping Strings in JavaScript

Steve Harrison picture Steve Harrison · Apr 21, 2009 · Viewed 127.5k times · Source

Does JavaScript have a built-in function like PHP's addslashes (or addcslashes) 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\".

Answer

Paolo Bergantino picture Paolo Bergantino · Apr 21, 2009

http://locutus.io/php/strings/addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}