简体   繁体   English

如何反转“String.fromCodePoint”,即将字符串转换为代码点数组?

[英]How do I reverse `String.fromCodePoint`, i.e. convert a string to an array of code points?

String.fromCodePoint(...[127482, 127480]) gives me a flag of the US (). String.fromCodePoint(...[127482, 127480])给了我一面美国国旗 ()。

How do I turn the flag back to [127482, 127480] ?如何将标志转回[127482, 127480]

You're looking for codePointAt , perhaps using spread (etc.) to convert back to array and then mapping each of them.您正在寻找codePointAt ,可能使用 spread (等)转换回数组,然后映射它们中的每一个。

console.log(theString.codePointAt(0)); // 127482
console.log(theString.codePointAt(2)); // 127480
// Note −−−−−−−−−−−−−−−−−−−−−−−−−−^
// It's 2 because the first code point in the string occupies two code *units*

or或者

const array = [...theString].map(s => s.codePointAt(0));
console.log(array); // [127482, 127480]

or skipping an interim step as Sebastian Simon pointed out via Array.from and its mapping callback:或者像 Sebastian Simon 通过Array.from及其映射回调指出的那样跳过一个中间步骤:

const array = Array.from(theString, s => s.codePointAt(0));
console.log(array); // [127482, 127480]

Example:例子:

 const theString = String.fromCodePoint(...[127482, 127480]); console.log(theString.codePointAt(0)); // 127482 console.log(theString.codePointAt(2)); // 127480 const array = [...theString].map(s => s.codePointAt(0)); console.log(array); // [127482, 127480] const array2 = Array.from(theString, s => s.codePointAt(0)); console.log(array2); // [127482, 127480]

Spread and Array.from both work by using the strings iterator , which works by code points, not code units like most string methods do. Spread 和Array.from都使用字符串迭代器工作,它通过代码点工作,而不是像大多数字符串方法那样工作的代码单元。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 String.fromCodePoint()不返回标志表情符号 - String.fromCodePoint() does not return flag emoji Unicode代理对和String.fromCodePoint()— JavaScript - Unicode surrogate pairs and String.fromCodePoint() — JavaScript 你可以像String.fromCharCode一样使用String.fromCodePoint吗? - Can you use String.fromCodePoint just like String.fromCharCode String.fromCodePoint / String#codePointAt(Firefox / ES6)的异常行为 - Unexpected behaviour of String.fromCodePoint / String#codePointAt (Firefox/ES6) String.fromCodePoint()在IE中不起作用,Tab键在Firefox中不起作用 - String.fromCodePoint() won't work in IE and tab key won't work in Firefox 如何使用正则表达式将字符串“ folder / lower-case-with-dash”转换为“ folderLowerCaseWithDash”(即,转换为camelCase格式)? - How can I convert string “folder/lower-case-with-dash” to “folderLowerCaseWithDash” (i.e. to camelCase format) using regex? 如何将Javascript字符串转换为数组? - How do I convert Javascript String into an Array? 将VBScript代码转换为javascript(即JScript)代码 - Convert VBScript code to javascript (i.e. JScript) code JavaScript将字符串转换为日期格式(dd mmm yyyy),即2012年6月1日 - JavaScript convert string into Date with format (dd mmm yyyy) i.e. 01 Jun 2012 如何在 for 循环中反转字符串? - How do I reverse a string within a for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM