Filtering empty strings from a string containing emojis using spread syntax

有些话、适合烂在心里 提交于 2019-12-11 06:34:46

问题


I'm trying to stay hip, so I've been playing with the spread operator and emojis. I noticed that when I want to filter empty strings ('') out the resulting "spread-ed" array, the empty strings are not being removed. Why is that?

console.log([...'😀︎']);                 // ['😀︎', '']
console.log([...'😀︎'].filter(String));  // ['😀︎', '']
console.log(['😀︎', ''].filter(String)); // ['😀︎']

回答1:


There is in your string an invisible character, which is a variation selector. You can see this if you print the character codes:

console.log([...'😀︎'].map(s => s.charCodeAt(0)));

If your goal is to remove that particular variation selector 15, then you could just use a replace:

s.replace(/\ufe0e/g, '')

Note how the emoji is slightly different in the output of the third statement you have. This is the effect of that variation selector, which you take away from the first character in the first two statements. Although that special character does not print anything on itself, and shows as an empty string when isolated, it really is not empty, and so filter will not exclude it.

Emoji characters themselves lie outside the single word UTF-16 range, and so they occupy two words.

When you split such a single-character string with split, you get two separate characters (a historic oddity of JavaScript), which represent the UTF encoding. If your goal is to count emojis (and other high-range characters) in your string, you could use this code:

console.log(s.split('').length - [...s].length);


来源:https://stackoverflow.com/questions/44979260/filtering-empty-strings-from-a-string-containing-emojis-using-spread-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!