user2406718
user2406718

Reputation: 263

Remove trailing and leading white spaces around delimiter using regex

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

Answers (2)

le_m
le_m

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

gcampbell
gcampbell

Reputation: 1272

You could use /\s*,\s*/g, and then .trim() the string.

Upvotes: 2

Related Questions