There are multiple ways how to strip emoji symbols from a string in JavaScript. Yet the combination of string.replace()
, string.trim()
methods and RegExp
works best in the majority of the cases.
First of all, we use replace()
and RegExp
to remove any emojis from the string.
At this point, you might think thatβs all that we need, but practically, we still need to handle cases where there is a sequence of emojis used which creates whitespace after truncation.
Then, we use replace()
and RegExp
once again. This time, we are only interested to remove multiple spaces. Worth mentioning that the starting and ending spaces will be kept and stripped down to a single space.
Finally, we use trim()
to remove any surrounding spaces from the string.
1const stripEmojis = (str) =>2 str3 .replace(4 /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g,5 ''6 )7 .replace(/\s+/g, ' ')8 .trim();9
10console.log(stripEmojis('π edvins.io'));11// Output: "edvins.io"12
13console.log(stripEmojis('π Kanye π Westπ π'));14// Output: "Kanye West"15
16console.log(stripEmojis('πaπbπcπdπeπfπgπh'));17// Output: "abcdefgh"18
19console.log(20 stripEmojis(21 "Lorem πIpsum is simply dummy text of the printing and πππtypesetting industry. Lorem Ipsum has been the industry's standard dummy π text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into π π π electronic typesetting, πremaining essentially unchanged. π It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of π Lorem Ipsum."22 )23);24// Output: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter