0

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.

2
  • 1
    Do you want to convert an arbitrary Javascript string into a JSON string value? Or do you want to escape just backslashes and some other characters? Give more examples of before/after. Commented Dec 14, 2011 at 16:56
  • I what to convert an arbitray JavaScript string into a JSON string value. Commented Dec 15, 2011 at 3:16

3 Answers 3

3

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 + '"';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'm just trying to embed the implementation for string in my code since my script may work in some place without `JSON.stringify.
2

If you just want to escape slashes and add quotes:

str = ['"', str.replace(/\\/g, '\\\\'), '"'].join('');

5 Comments

Ah, I forgot about the outer quotes. +1
Default join behavior is to join with commmas
Still not a good answer, doesn't do one tenth of the job that JSON.stringify does.
@JuanMendes: Which is not required as far I understood. OP should clarify his question then.
@FelixKling: It's clear from the question that OP wants the same behavior as JSON.stringify. I hope you wouldn't take a poorly written requirement and implement it to the letter, knowing that it very likely doesn't do the job/
0

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.

1 Comment

I initially thought it wouldn't work... but it does. Just need to wrap it with quotes. The only problem is that it encodes too much. Since the OP seemed concerned with performance, going through the string twice (escape and replace) it would seem like too much work. escape("Hello world % & = '' \n \t \" ] ").replace(/%/g, '\\x'); // output: "Hello\x20world\x20\x25\x20\x26\x20\x3D\x20\x27\x27\x20\x0A\x20\x09\x20\x22\x20\x5D\x20"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.