Convert this unicode to string with javascript (Thai Language) - Stack Overflow

มอเตอร์ไซ&

มอเตอร์ไซค์

Can I convert this unicode to string with JS. (It is Thailand Language)

I use

console.log(String.fromCharCode("มอเตอร์ไซค์"));

And It's not correct. if it right it will show มอเตอร์ไซค์

มอเตอร์ไซค์

Can I convert this unicode to string with JS. (It is Thailand Language)

I use

console.log(String.fromCharCode("มอเตอร์ไซค์"));

And It's not correct. if it right it will show มอเตอร์ไซค์

Share Improve this question asked Jul 17, 2015 at 12:21 Tol Thailand ProgrammerTol Thailand Programmer 611 silver badge8 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

Your Unicode string is encoded using HTML entity notation. Generally that means that whatever encoded the string expected it to end up in the middle of an HTML document, where it would be seen by an HTML parser.

If you've somehow got that string in JavaScript in a browser, you can get to the encoded Unicode by letting the browser parse it:

var str = "มอเตอร์ไซค์";
var elem = document.createElement("div");
elem.innerHTML = str;
alert(elem.textContent);

The string.fromCharCode() function expects one or more numeric arguments; it won't understand HTML entities. Thus if you're not in a browser (like, if you've got the string in a Node.js program or something like that), you could convert the string with your own code:

var str = "มอเตอร์ไซค์";
var thai = String.fromCharCode.apply(String, str.match(/x[^;]*;/g).map(function(n) { return parseInt(n.slice(1, -1), 16); }));

That conversion will only work when the code points involved are within the first 64K values.

You may want something like this :

var input = "มอเตอร์ไซค์";

var output = input.replace(/&#x[0-9A-Fa-f]+;/g,
                           function(htmlCode) {
                               var codePoint = parseInt( htmlCode.slice(3, -1), 16 );
                               return String.fromCharCode( codePoint );
                           });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745370107a4624758.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信