首页 > 解决方案 > ES2015 string iterator information about index

问题描述

In ES2015 or ES6, strings are iterable. This feature can be used to handle Unicode surrogate pairs properly.

For example,

const str = "a\u{1F436}b";
for (const ch of str) {
    f(ch);
}

will call f() 3 times whereas

const str = "a\u{1F436}b";
for (let i = 0; i < str.length; i++) {
    f(ch[i]);
}

will call f() 4 times.

What I want to do is getting the beginning or ending indices of those characters. For example, for str = "a\u{1F436}b", I want to get something like [0, 1, 3] because each unicode character starts at the index 0, 1, 3 respectively.

However, the iterator does not seem to give information about the index.

How can I get the indices?

标签: javascriptstringecmascript-6unicode

解决方案


做这样的事情怎么样

var str = "a\u{1F436}b";

let current = 0
let indexes = [...str].map(a=> {
  let temp = current
  current += a.length
  return temp
})

console.log(indexes)

String Split With Unicode


推荐阅读