blueSky
blueSky

Reputation: 247

replace non-alphamumeric and multiple spaces

I have this regex to remove all non-alphanumeric characters.

a = a.replace(/[^0-9a-z]+/gi,'');

Any help to add to this line to replace all multiple spaces with a single space.

Thanks.

Upvotes: 0

Views: 70

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

To achieve this in a single regular expression, you can alternate with capturing the space in a group, and then replace with that group (which will be the empty string if the other alternation was used):

const replace = str => str.replace(/( )+|[^\da-z ]+/gi, '$1');
console.log(replace('foobar'));
console.log(replace('foo       bar'));
console.log(replace('foo###bar'));

Also note that 0-9 can be replaced with \d, which is a bit nicer to read IMO.

Upvotes: 1

Related Questions