javascriptsplitescaping

Unescape string in JavaScript (without using JSON.parse)


I am trying to unscape a string (get the original \t character).

I have been trying all this:

var s = "my \t string";
var t = "\\t"; // Backslashes are escaped because this is rendered on an <input>

// How do we split the string?

s.split(t); // ["my      string"]
s.split(t.substring(1)); // Not working becuase t.substring(1) is just 't'
s.split(t.replace(/\\\\/g, "\\")); // ["my   string"]

// Expected result would be:

s.split('\t'); // ["my ", " string"]

// Using JSON.parse works

s.split(JSON.parse('"' + t + '"')); // ["my ", " string"]

Is JSON.parse the only way of doing it?


Solution

  • JSON.parse is not the only way. You can also use RegExp, as in regex notation a TAB character can be represented as the character pair \t, which is what you have in the variable t:

    var s = "my \t string"; // A string containing a TAB character
    var t = "\\t"; // A backslash followed by "t"
    
    const parts = s.split(RegExp(t));
    console.log(parts);  // ["my ", " string"]