dhrm
dhrm

Reputation: 14934

How to convert unicode in JavaScript?

I'm using the Google Maps API. Please see this JSON response.

The HTML instructions is written like this:

"html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e"

How can I convert the unicodes \u003c, \u003e etc. in JavaScript?

Upvotes: 9

Views: 46417

Answers (4)

Below is a simpler way thanks to modern JS .

ES6 / ES2015 introduced the normalize() method on the String prototype, so we can do:

var directions = "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e";

directions.normalize();

//it will return : "Turn <b>left</b> onto <b>Enggårdsgade</b>"

Refer to this article : https://flaviocopes.com/javascript-unicode/

Upvotes: 7

Yogesh Agrawal
Yogesh Agrawal

Reputation: 982

This small function may help

String.prototype.toUnicode = function(){
    var hex, i;
    var result = "";
    for (i=0; i<this.length; i++) {
        hex = this.charCodeAt(i).toString(16);
        result += ("\\u00"+hex).slice(-7);
    }

    return result;
};

Upvotes: -1

Saket Patel
Saket Patel

Reputation: 6683

you can use JSON.parse directly on JSON response then the unicode characters will automatically converted to its html counter parts (\u003c will be converted to < sign in html)

JSON.parse(JSON.stringify({a : 'Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e'}));

Upvotes: 5

Mathias Bynens
Mathias Bynens

Reputation: 149534

Those are Unicode character escape sequences in a JavaScript string. As far as JavaScript is concerned, they are the same character.

'\u003cb\u003eleft\u003c/b\u003e' == '<b>left</b>'; // true

So, you don’t need to do any conversion at all.

Upvotes: 11

Related Questions