0

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.

1
  • 1
    JSON specs do not have any ASCII escape characters only unicode. json.org/json-en.html Commented Feb 13, 2021 at 22:36

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I'm just astonished that functionality like this isn't built into the language and requires us to manually pick apart the string, especially since JavaScript's own interpreter does support ascii escaped characters. Still, thanks for your help.
@mt_xing yeah - also you'd think that JSON.parse might be able to deal with both formats. Anyway... I'm glad this was helpful.
-1

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"

Comments

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.