Javascript – Escaping Strings in JavaScript

backslashescapingjavascriptquotesstring

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\".

Best Solution

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

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