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.
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 quotesHere’s a blatant copy of the code from json.org that does what you need. http://jsfiddle.net/mendesjuan/rFCwF/