[英]How to split string into characters but to keep spaces in javascript
[英]How to split Unicode string to characters in JavaScript
長期以來,我們使用幼稚的方法在 JS 中拆分字符串:
someString.split('');
但是表情符號的流行迫使我們改變這種做法——表情符號字符(和其他非 BMP 字符)就像是由兩個“字符”組成的。
String.fromCodePoint(128514).split(''); // array of 2 characters; can't embed due to StackOverflow limitations
那么,什么是現代、正確和高效的方法來完成這項任務呢?
此任務的最佳方法是使用可String.prototype[Symbol.iterator]
Unicode 字符的原生String.prototype[Symbol.iterator]
。 因此,分割 Unicode 字符的Array.from
方法是Array.from
用於字符串,例如:
const string = String.fromCodePoint(128514, 32, 105, 32, 102, 101, 101, 108, 32, 128514, 32, 97, 109, 97, 122, 105, 110, 128514);
Array.from(string);
ECMA 2015 中引入了一個標志來支持正則表達式中的 unicode 感知。
將u
添加到您的正則表達式會在您的結果中返回完整的字符。
const withFlag = `AB😂DE`.match(/./ug); const withoutFlag = `AB😂DE`.match(/./g); console.log(withFlag, withoutFlag);
有一個小更多關於它在這里
我在某個地方做了類似的事情,我必須支持舊瀏覽器和 ES5 縮小器,可能對其他人有用
if (Array.from && window.Symbol && window.Symbol.iterator) {
array = Array.from(input[window.Symbol.iterator]());
} else {
array = ...; // maybe `input.split('');` as fallback if it doesn't matter
}
JavaScript 有一個名為Intl.Segmenter
的新 API(ES2023 的一部分),允許您根據字形(字符串的用戶感知字符)拆分字符串。 使用此 API,您的拆分可能如下所示:
const split = (str) => { const itr = new Intl.Segmenter("en", {granularity: 'grapheme'}).segment(str); return Array.from(itr, ({segment}) => segment); } // See browser console for output console.log(split('')); // [''] console.log(split('é')); // ['é'] console.log(split('')); // [''] console.log(split('❤️')); // ['❤️'] console.log(split('♀️')); // ['♀️']
<p>See browser console for logs</p>
這使您不僅可以處理由兩個代碼點組成的表情符號,例如 , 但其他字符也如復合字符(例如:
é
),由 ZWJ 分隔的字符(例如: ),帶有變體選擇器的字符(例如:❤️),帶有表情符號修飾符的字符(例如:
♀️
)等。所有這些都無法通過調用字符串的迭代器(通過使用 spread ...
, for..of
, Symbol.iterator
等),如其他答案所示,因為這些只會迭代字符串的代碼點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.