Javascript 如何反转 String.fromCharCode?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2071602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:39:34  来源:igfitidea点击:

How to reverse String.fromCharCode?

javascriptcharreverse

提问by IAdapter

String.fromCharCode(72) gives H. How to get number 72 from char H?

String.fromCharCode(72) 给出 H。如何从字符 H 中获取数字 72?

回答by Silvio Donnini

'H'.charCodeAt(0)

回答by Tatu Ulmanen

Use charCodeAt:

使用 charCodeAt:

var str = 'H';
var charcode = str.charCodeAt(0);

回答by theicfire

@Silvio's answer is only true for code points up to 0xFFFF (which in the end is the maximum that String.fromCharCode can output). You can't always assume the length of a character is one:

@Silvio 的答案仅适用于高达 0xFFFF 的代码点(最终是 String.fromCharCode 可以输出的最大值)。你不能总是假设一个字符的长度是 1:

''.length
-> 2

Here's something that works:

这是有效的方法:

var utf16ToDig = function(s) {
    var length = s.length;
    var index = -1;
    var result = "";
    var hex;
    while (++index < length) {
        hex = s.charCodeAt(index).toString(16).toUpperCase();
        result += ('0000' + hex).slice(-4);
    }
    return parseInt(result, 16);
}

Using it:

使用它:

utf16ToDig('').toString(16)
-> "d800df30"

(Inspiration from https://mothereff.in/utf-8)

(灵感来自https://mothereff.in/utf-8

回答by David Refoua

You can define your own global functions like this:

您可以像这样定义自己的全局函数:

function CHR(ord)
{
    return String.fromCharCode(ord);
}

function ORD(chr)
{
    return chr.charCodeAt(0);
}

Then use them like this:

然后像这样使用它们:

var mySTR = CHR(72);

or

或者

var myNUM = ORD('H');

(If you want to use them more than once, and/or a lot in your code.)

(如果你想多次使用它们,和/或在你的代码中使用很多。)

回答by Gunar Gessner

String.fromCharCodeaccepts multiple arguments, so this is valid

String.fromCharCode接受多个参数,所以这是有效的

const binaryArray = [10, 24] // ...
str = String.fromCharCode(...binaryArray)

In case someone comes looking for the opposite for that(like I did), this might come in handy

万一有人来寻找相反的(像我一样),这可能会派上用场

const binaryArray = str
  .split('')
  .reduce((acc, next) =>
    [...acc, next.charCodeAt(0)],
    []
  )