Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace punctuation with whitespace

I have a word counter function but it doesn't account for people using poor punctuation, for example:

"hello.world"

That would only count is as 1 word.

Instead it should count that as 2 words.

So instead I need a regex to replace comma's, full stops and any whitespace that is 1+ with a single whitespace.

Here's what I have so far:

proWords = proWords.replace(/[,\s]/, '\s');

negWords = negWords.replace(/[,\s]/, '\s');
like image 711
Philip Richardson Avatar asked Mar 25 '26 05:03

Philip Richardson


1 Answers

The replacement is just an ordinary string, it shouldn't contain regular expression escape sequences like \s.

proWords = proWords.replace(/[,.\s]+/g, ' ');

The + regular expression makes it replace any sequence of the characters, and you need the g modifier to replace multiple times.

like image 51
Barmar Avatar answered Mar 26 '26 18:03

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!