0

I have a quick question.

This is my code, and problem with it is when i run some emojis thro this it displays them as ?, cause it cuts the emoji in half.

angular.module('Joe.filters').filter("initials", function() {
    return function(string) {
        if (string) {
            var words = string.split(" ");
            if (words.length) {
                string = words[0].charAt(0);
                if (words[1]) {
                    string += words[1].charAt(0);
                }
            }
        }

        return string;
    };
});

Now, im thinking if i can solve this with toArray, and if yes, how? Note: if i run in console the "fix" with array.

j = '';
""

j.length
2

s = _.toArray(j)
[""]

s.length
1

Thanks in advance!!

joe123
  • 47
  • 1
  • 7

1 Answers1

1

In ES6, .charAt and [indexing] still work with 16-bit units, but String.iterator is aware of 32-bit chars. So, to extract the first char which is possibly beyond the plane 0, you have to force iteration on the string, for example:

word = 'HELLO';

let b = [...word][0]
// or
let [c] = word

console.log(b, c)

Another option is to extract the first code point and convert it back to a character:

let a = String.fromCodePoint(word.codePointAt(0))

To answer the bonus question, I have this rather trivial function in my "standard repertoire"

let first = ([a]) => a

Using this func, your initials logic can be written as

let initials = str => str.split(' ').slice(0, 2).map(first).join('')
georg
  • 211,518
  • 52
  • 313
  • 390