Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to remove zero-width space characters from a JavaScript string.

In this article, we’ll look at how to remove zero-width space characters from a JavaScript string.

Remove Zero-Width Space Characters from a JavaScript String

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-u200DuFEFF]/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.

Conclusion

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 replaces them with empty strings.

By John Au-Yeung

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

Leave a Reply

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