Reputation: 247
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
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