Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
dhrm Avatar asked Mar 29 '12 20:03

dhrm


People also ask

Can I use Unicode in JavaScript?

In Javascript, the identifiers and string literals can be expressed in Unicode via a Unicode escape sequence. The general syntax is \uXXXX , where X denotes four hexadecimal digits. For example, the letter o is denoted as '\u006F' in Unicode.

Can we convert Unicode to text?

World's simplest unicode tool. This browser-based utility converts fancy Unicode text back to regular text. All Unicode glyphs that you paste or enter in the text area as the input automatically get converted to simple ASCII characters in the output.

How do I convert Unicode to ASCII?

You CAN'T convert from Unicode to ASCII. Almost every character in Unicode cannot be expressed in ASCII, and those that can be expressed have exactly the same codepoints in ASCII as in UTF-8, which is probably what you have.

Does JavaScript use UTF-8 or UTF-16?

UTF-16 is used by systems such as the Microsoft Windows API (which also supports UTF-8 though), the Java programming language and JavaScript/ECMAScript. It is also sometimes used for plain text and word-processing data files on Microsoft Windows.


2 Answers

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.

like image 155
Mathias Bynens Avatar answered Oct 02 '22 23:10

Mathias Bynens


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/

like image 27
Daggie Blanqx - Douglas Mwangi Avatar answered Oct 02 '22 21:10

Daggie Blanqx - Douglas Mwangi