Gilbert
Gilbert

Reputation: 921

Stuck With Weird Encoding in Javascript

I'm working with a third party API (i.e Read it Later API) and I notice that all the strings are being returned in the following format:

http:\/\/www.fourhourworkweek.com\/blog\/2007\/11\/07\/how-to-learn-b Philip Greenspun's Weblog \u00bb Stupid white man criticizes smart Chinese woman

Now, I know that '\' is really a '\' and that "\u00bb" really stands for \u00bb, which stands for '»'.

But how exactly would I decode that using Javascript?

Upvotes: 0

Views: 192

Answers (3)

Quentin
Quentin

Reputation: 944524

This string has been JavaScript escaped and then HTML encoded.

So first you have to decode the HTML:

var foo = "http:\/\/www.fourhourworkweek.com\/blog\/2007\/11\/07\/how-to-learn-b Philip Greenspun's Weblog \u00bb Stupid white man criticizes smart Chinese woman";

var element = document.createElement('div');
element.innerHTML = foo;
foo = element.firstChild.data;

and then the JavaScript.

Unfortunately, I don't know a good way to do this, so I am resorting to eval. Please comment if you can spot a better way!

foo = eval("'" + foo.replace("'", "\\'").replace('\n', '\\n') + "'");
alert(foo);

Upvotes: 2

ilivewithian
ilivewithian

Reputation: 19712

The string looks escaped, try running your string through the unescape(string) function in javascript, that should give you back the original version.

Upvotes: -1

RAMe0
RAMe0

Reputation: 1267

Why don't you are using str.replace? Like this:

    var str="http:\/\/www.fourhourworkweek.com\/blog\/2007\/11\/07\/how-to-learn-b Philip Greenspun's Weblog \u00bb Stupid white man criticizes smart Chinese woman";
    str=str.replace (/\/ig,"\\"); 

results on JSfiddle

Upvotes: 0

Related Questions