Skip to content

Edvins Antonovs

How to strip emojis from string in JavaScript

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 str
3 .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."

Appendix

Join the newsletter

For monthly notes on software development and entrepreneurship.

Β© 2022 by Edvins Antonovs. All rights reserved.