I have a string that I got by using Ajax to load a preview of a web page. The title comes out like this:
You Can\xe2\x80\x99t Handle the Truth About Facebook Ads, New Harvard Study Shows
I need to replace those escape codes with human readable text. I have tried String.fromCharCode()
, but that doesn't return anything in the case of a mixed string, only if you send it character codes only.
Is there a function I can use to fix this string?
Here's one way to do it:
const str_orig = 'You Can\\xe2\\x80\\x99t Handle the Truth About Facebook Ads, New Harvard Study Shows';
console.log("Before: " + str_orig);
const str_new = str_orig.replace(
/(?:\\x[\da-fA-F]{2})+/g,
m => decodeURIComponent(m.replace(/\\x/g, '%'))
);
console.log("After: " + str_new);
The idea is to replace \x
by %
in the string (which produces a URL encoded string), then apply decodeURIComponent
, which handles UTF-8 decoding for us, turning %e2%80%99
into a single character: ’
(U+2019, RIGHT SINGLE QUOTATION MARK).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With