Javascript Substring Without Splitting Emoji
in my js I am trying to substring() text which generally works but unfortunately decapitates emojis. usaText = 'A🇺🇸Z' splitText = usaText.substring(0,2) //'A�' splitText =
Solution 1:
So this isn't really an easy thing to do, and I'm inclined to tell you that you shouldn't write this on your own. You should use a library like runes.
Just a simple npm i runes
, then:
const runes = require('runes');
const usaText = "A🇺🇸Z";
runes.substr(usaText, 0, 2); // "A🇺🇸"
Solution 2:
Solution 3:
Disclaimer: This is just extending the above comment by Mike 'Pomax' Kamermans because to me it is actually a much simpler, applicable answer (for those of us who don't like reading through all the comments):
Array.from(str) splits your string into individual unicode characters without breaking them between bytes.
See Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters") for details.
Post a Comment for "Javascript Substring Without Splitting Emoji"