Categories
JavaScript Answers

How to Remove Zero-Width Space Characters from a JavaScript String?

Spread the love

To remove zero-width space characters from a JavaScript string, we can use the JavaScript string replace method that matches all zero-width characters and replace them with empty strings.

Zero-width characters in Unicode includes:

  • U+200B zero width space
  • U+200C zero-width non-joiner Unicode code point
  • U+200D zero width joiner Unicode code point
  • U+FEFF zero-width no-break space Unicode code point

For instance, we can do the replacement by writing:

const userInput = 'au200Bbu200Ccu200DduFEFFe';
console.log(userInput.length);
const result = userInput.replace(/[\u200B-\u200D\uFEFF]/g, ”);
console.log(result.length);

We have the userInput string that has the zero-width characters listed.

From the first console log, we see userInput.length is 9.

Then we call replace with a regex that matches the zero-width characters listed and replaces them all with empty strings.

And so we see that result.length is 5, so the zero-width characters were removed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

3 replies on “How to Remove Zero-Width Space Characters from a JavaScript String?”

Very handy. And here I was thinking RegEx was just what women did to me every time I ask them on dates… which reminds me, if there are any single ladies reading this, I’d like to put a zero-width word joiner, between U and ME 🔨😎 Nailed it 👏 I may like unicode but I am no eunuchode. Think I’m good at word play? Let’s make it…bird play? (eh 🫤 2 out of 3)

Leave a Reply

Your email address will not be published. Required fields are marked *