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 spaceU+200C
zero-width non-joiner Unicode code pointU+200D
zero width joiner Unicode code pointU+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.
3 replies on “How to Remove Zero-Width Space Characters from a JavaScript String?”
Thanks for this! Solved my issue. One thing to note, example is missing backslash. It should be:
replace(/[\u200B-\u200D\uFEFF]/g, ”)
Thanks. I fixed the typos.
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)