Home > Net >  JavaScript Regex: Removing all whitespaces only between commas [duplicate]
JavaScript Regex: Removing all whitespaces only between commas [duplicate]

Time:09-30

String: word, word , word word , word

Regex: ^\s |\s $|\s(?=[\s,])

This regex will remove all leading, trailing and all whitespaces before commas. How to additional remove whitespaces after commas but not between words (between 3 & 4 word)?

What I want as a result: word,word,word word,word

CodePudding user response:

You want to select the commas and the whitespaces around and replace them with only a comma, you can use \s*,\s*, for that.

For the leading and trailing whitespaces use a distinct regex or simply the builtin 'trim' function in your language.

You don't need look-arounds.

Here's a visualization of the regex: https://regex101.com/r/VPwC17/2

  • Related