问题
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