Javascript's string literals use those same backslash escapes. There should be a way to make use of that...
var escapedString = '\\t' // actually contains "\t"
, renderedString = (new Function('return "' + text + '"'))()
;
console.log(renderedString); // " " <= this is the tab character
Note that this leaves your code wide open for injection attacks, and is very unsafe, especially if the escapedString
is coming from an external source!
It’s (almost) as bad as using eval!
Update: the safe way
A better way would probably be using a regular expression:
var escapedString = '\\t' // actually contains the characters \ and t
, renderedString = escapedString.replace(/\\(.)/g, function (match, char) {
return {'t': '\t', 'r': '\r', 'n': '\n', '0': '\0'}[char] || match;
}
;
console.log(renderedString); // " " <= this is the tab character
Here you’d be using the replace method to track down all the backslashes (followed by any character) in the given string, and call the anonymous function every time a match is found. The function's returned value will determine what that match will be replaced by.
The anonymous function contains a JS object (in this case used as an associative array), which contains all the recognized escape characters. The character following the backslash (here called char
), will be looked up in that associative array, and JS will return the corresponding value.
The final part of the line, || char
, ensures that if the char
is not part of the associative array, the unchanged match is used (which includes the backslash), leaving the original string unchanged.
Of course, this does mean that you have to specify all the possible escapes in advance.
Second update: the way to go
It just occurred to me that the first method is unsafe (there might be fraudulent input), and the second method uncertain (you don't really know what escapes you need to provide for); perhaps both methods could be combined!
var escapedString = '\\t' // actually contains the characters \ and t
, renderedString = escapedString.replace(/\\./g, function (match) {
return (new Function('return "' + match + '"'))() || match;
}
;
console.log(renderedString); // " " <= this is the tab character
Of course, the performance of this solution won't be very great. Parsing and building that new function is a costly thing, and it needs to be done for each and every matching backslash present in the escaped string. If performance becomes an issue, you could add some kind of caching mechanism, which remembers each function once it's been created.
Then again, you could also look up the API you need to work with, try and find its documentation or contact its makers, and get a definitive list of escapes it can produce. :-0