Steve Harrison Steve Harrison - 6 days ago 6
Javascript Question

Escaping Strings in JavaScript

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

http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_addslashes/

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