Reputation: 5023
Say I have a string value a\bc
keeps in a variable, how can I turn it into a string in code like "a\\bc"
? The string may contains tabs, slashes, new lines, etc.
I know there's a build-in JSON.stringify
method in some browsers and there's a JSON2 lib but I just want to have a minimum piece of code can do the job only for string.
Upvotes: 0
Views: 207
Reputation: 92274
Sounds like premature optimization. Unless you have a problem with performance, I'd go with JSON.stringify
, no extra code to write, no need to figure out how to encode it.
None of the answers here are good enough, since they don't encode all the possible things like \n, \r, \t or quotes
Here's a blatant copy of the code from json.org that does what you need. http://jsfiddle.net/mendesjuan/rFCwF/
function quote(string) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
}
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
Upvotes: 3
Reputation: 2755
If you need a safe method to "escape" your strings, try this:
escape(str).replace(/%/g, '\\x')
It uses the internal escape
function, then, converts the %-url escape format to -string escape format.
Upvotes: 0
Reputation: 816384
If you just want to escape slashes and add quotes:
str = ['"', str.replace(/\\/g, '\\\\'), '"'].join('');
Upvotes: 2