mt_xing
mt_xing

Reputation: 653

Parse Ascii Escaped String in JavaScript

Say we're given a string that itself contains ASCII escape characters, such as "\x64" (note that this is the contents of the string, not what it would be in code). Is there an easy way in JavaScript to parse this to its actual character?

There's the old trick of using JSON.parse but that seems to only work with unicode escape sequences and can't recognize ASCII ones, as in:

JSON.parse(`"\\u0064"`); // Output: "d" (as expected)
JSON.parse(`"\\x64"`);   // ERROR: Unexpected token x

Is there an equivalent that would work for the ASCII escape sequence? I know that using eval() works but I'd really rather not use eval.

EDIT: To clarify, some characters in the original string may not be escaped; as we may need to parse "Hello Worl\x64", for instance.

Upvotes: 0

Views: 415

Answers (2)

xavi
xavi

Reputation: 76

You can use the eval function to evaluate a string in the same way it would be evaluated from Javascript source code, you'll only need to make sure you quote its content as such:

eval("\"\\x64\"") // will return the javascript string: "d"

Upvotes: -1

Nick
Nick

Reputation: 147206

One solution is to replace all the \x** patterns in the string, using a callback to parse them as base 16 integers and pass the result to String.fromCharCode to convert to a character:

const str = "\\x48\\x65ll\\x6f\\x20W\\x6f\\x72\\x6c\\x64";
const res = str.replace(/\\x(..)|./g, (m, p1) => p1 ? String.fromCharCode(parseInt(p1, 16)) : m);
console.log(res);

If you don't mind overwriting the original string, this can be simplified slightly to:

let str = "\\x48\\x65ll\\x6f\\x20W\\x6f\\x72\\x6c\\x64";
str = str.replace(/\\x(..)/g, (m, p1) => String.fromCharCode(parseInt(p1, 16)));
console.log(str);

Upvotes: 3

Related Questions