Javascript, handling escape characters

Asked

Viewed 507 times

1

In a function I get strings in this template

message="'J\\xe1'"; //sendo '\xe1' = á 

I need to turn these bars " " into a single bar ' ' ' to get the Unicode code ace, where this string can be any sentence and the bars can be anywhere and appear in more than one place.

  • In fact I get these variables by python, my html code is manipulated by python through Selenium.

  • This information comes from a database

  • Yes, Selenium browses web pages, but in my application it takes data from DB and inserts it into pages

  • Yeah, like I said, the problem could be how you take this data and maybe you’re using a solution to solve a problem that maybe didn’t even have to exist, but I’m just saying this because I wanted to give you a strength to work around the problem more efficiently, But if it’s all right with you. until next and a good evening

  • In fact, the problem arises when python has difficulties working directly with characters outside of ASCII, so instead of working with bytes, I went straight to Unicode code

1 answer

2


I don’t know if this string is trustworthy... if it’s a secure string you could use the eval thus:

const message = "'J\\xe1'";
const parsed = eval(message);
console.log(parsed); // Já

But the safest thing is to use the decodeURI, identify all hexadecimal characters and replace them one by one like this:

const REGEX = /\\x([a-fA-F0-9]{2})/g;
const hex2char = (str, hex) => {
  return String.fromCharCode(parseInt(hex, 16));
}

const message = "'J\\xe1 n\\xe3o tenho fome!'";
const unescaped = decodeURI(message.slice(1, -1));

const text = unescaped.replace(REGEX, hex2char);

console.log(text);

  • 1

    The second solution worked perfectly, the sentence is passed from python through the Lenium library, and python has that difficulty with Unicode, that was the output I found. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.