最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

utf 8 - Error on concatenate utf strings in javascript - Stack Overflow

programmeradmin5浏览0评论

I am trying to concatenate a strings and print its utf8 character. However that doesn't seem to be the correct syntax for some reason. The error is:

 console.log("\u" + i);
            ^^^
 SyntaxError: Unexpected token ILLEGAL

The code used to generate is

var _ = require('lodash');

_.times(2588, function(i){
    console.log("\u" + i);
});

I am trying to concatenate a strings and print its utf8 character. However that doesn't seem to be the correct syntax for some reason. The error is:

 console.log("\u" + i);
            ^^^
 SyntaxError: Unexpected token ILLEGAL

The code used to generate is

var _ = require('lodash');

_.times(2588, function(i){
    console.log("\u" + i);
});
Share Improve this question edited Jan 13, 2016 at 23:39 filype asked Nov 14, 2015 at 8:15 filypefilype 8,41010 gold badges46 silver badges69 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 7

You can use String.fromCharCode

E.g. String.fromCharCode(0x2588) == "\u2588"

The SyntaxError is because "\u" is not valid unicode sequence.

Assuming you want to create dynamic sequence with the \u prefix , you can do this :

//65 --> 0065
Number.prototype.pad = function(size) {
      var s = String(this);
      while (s.length < (size || 2)) {s = "0" + s;}
      return s;
    }

for (var i=6000;i<6005;i++) // for example...
{
 alert(unescape ('%u' + i.pad(4)))
}

Result :

怀
态
怂
怃
怄

http://jsbin./vogeqotoqa/edit?html,js,output

There are two issues here:

1) When you concatenate the string and the number representing the utf sequence javascript attempts to parse the "\u" as a unicode character, if you try console.log("\u0000"+0) the result will be �0

2) UTF 8 sequences must contain 4 hexadecimal characters, \u0 is not a valid unicode sequence while \u0000 is. Unicode sequences obey this regular expression: \u[a-fA-F0-9]{4}

The correct answer is Akisame's, use console.log(String.fromCharCode(i));. Also see Generate a list of unicode characters in a for loop

var message="здравей";
var final=message.concat(" готин"," свят");
alert(final);
发布评论

评论列表(0)

  1. 暂无评论