在JavaScript中与Python的chr()相对应

JavaScript方法String.fromCharCode()行为等同于Python的unichar() ,其含义如下:

 print unichr(213) # prints Õ on the console console.log(String.fromCharCode(213)); // prints Õ on the console as well 

但是,为了我的目的,我需要一个与Python函数chr()相当的JavaScript。 有没有这样的JavaScript函数或方式使String.fromCharCode()行为像chr()

也就是说,我需要一些模仿JavaScript的东西

 print chr(213) # prints   on the console 

原来你只是想在node.js中使用原始字节, 这里有一个模块 。 如果你是一个真正的向导,你可以单独使用javascriptstring来处理这些东西,但是效率更高,效率更低。

 var b = new Buffer(1); b[0] = 213; console.log(b.toString()); //  var b = new Buffer(3); b[0] = 0xE2; b[1] = 0x98; b[2] = 0x85; console.log(b.toString()); //★ 

print chr(213) # prints on the console

因此,这将打印一个原始字节( 0xD5 ),这是UTF-8(很有可能)解释,这是不是有效的UTF-8字节序列,因此显示为replace字符( )。

作为UTF-8的解释在这里是不相关的,你很可能只是想要原始字节。

要在JavaScript中创build原始字节,您可以使用UInt8Array

 var a = new Uint8Array(1); a[0] = 213; 

您可以select将原始字节解释为utf-8:

 console.log( utf8decode(a)); // " " //Not recommended for production use ;D //Doesn't handle > BMP to keep the answer shorter function utf8decode(uint8array) { var codePoints = [], i = 0, byte, codePoint, len = uint8array.length; for (i = 0; i < len; ++i) { byte = uint8array[i]; if ((byte & 0xF8) === 0xF0 && len > i + 3) { codePoint = ((byte & 0x7) << 18) | ((uint8array[++i] & 0x3F) << 12) | ((uint8array[++i] & 0x3F) << 6) | (uint8array[++i] & 0x3F); if (!(0xFFFF < codePoint && codePoint <= 0x10FFFF)) { codePoints.push(0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD); } else { codePoints.push(codePoint); } } else if ((byte & 0xF0) === 0xE0 && len > i + 2) { codePoint = ((byte & 0xF) << 12) | ((uint8array[++i] & 0x3F) << 6) | (uint8array[++i] & 0x3F); if (!(0x7FF < codePoint && codePoint <= 0xFFFF)) { codePoints.push(0xFFFD, 0xFFFD, 0xFFFD); } else { codePoints.push(codePoint); } } else if ((byte & 0xE0) === 0xC0 && len > i + 1) { codePoint = ((byte & 0x1F) << 6) | ((uint8array[++i] & 0x3F)); if (!(0x7F < codePoint && codePoint <= 0x7FF)) { codePoints.push(0xFFFD, 0xFFFD); } else { codePoints.push(codePoint); } } else if ((byte & 0x80) === 0x00) { codePoints.push(byte & 0x7F); } else { codePoints.push(0xFFFD); } } return String.fromCharCode.apply(String, codePoints); } 

但是你最有可能试图做的事情与试图把字节解释为utf8无关。

另一个例子:

 //UTF-8 For the black star U+2605 ★: var a = new Uint8Array(3); a[0] = 0xE2; a[1] = 0x98; a[2] = 0x85; utf8decode(a) === String.fromCharCode(0x2605) //True utf8decode(a) // ★ 

在python 2.7(Ubuntu)中:

 print chr(0xE2) + chr(0x98) + chr(0x85) #prints ★ 

如果你想为每个不在标准ASCII表格中的数字设置“Questionmark in a box”,这个小函数怎么样?

 function chr(c) { return (c < 0 || c > 126) ? ' ' : String.fromCharCode(c); } 
Interesting Posts