I’m working on a JavaScript program that’s parsing data from an API. Part of the data is coming back in the format ‘\t’ etc and I need to parse it as tab (in this example) not ‘\t’.
In PHP, there’s a wonderful function called stripcslashes() which does this for me, but I can’t find a JavaScript equivalent.
Does anyone know of such a function in JavaScript? Or a way of parsing ‘\t’ as a tab?
Javascript’s string literals use those same backslash escapes. There should be a way to make use of that…
Note that this leaves your code wide open for injection attacks, and is very unsafe, especially if the
escapedStringis 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:
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 thecharis 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!
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