Reputation: 263
I am trying to remove white spaces from a string. However, I want to remove spaces around the delimiter and from beginning and ending of the string.
Before:
" one two, three , four ,five six,seven "
After:
"one two,three,four,five six,seven"
I've tried this pattern without success:
/,\s+|\s$/g,","
Upvotes: 1
Views: 586
Reputation: 20228
Use the regex ^\s+|(,)\s+|\s+(?=,)|\s$
and replace matches with the first capturing group $1
:
var string = " one two, three , four ,five six,seven ";
console.log(string.replace(/^\s+|(,)\s+|\s+(?=,)|\s$/g, '$1'));
The capturing group is either empty or contains a comma when the regex engine encounters a space after a comma (,)\s+
(for which we would better use lookbehind, but JavaScript does not support it).
Upvotes: 1