0

I have a string that looks like this:

var string = 'Size? [Small] Color? [Blue]'

I want to remove all non alphanumeric but keep spaces and []

The end string would be

'Size [Small] Color [Blue]'

I tried the \W like this:

string = string.replace(/\W/g, '')

But that gets rid of the spaces and the []

I'm not sure how to exclude and include items in a regular expression?

1

2 Answers 2

3

\W matches all non-word characters.

To match all non alpha-numerals except space, [ and ] you should use a negated character class:

/[^a-zA-Z0-9 \[\]]/

RegEx Demo

Code:

let string = 'Size? [Small] Color? [Blue]';

string = string.replace(/[^a-zA-Z0-9 \[\]]+/g, '') 

console.log( string );
//=> Size [Small] Color [Blue]

Sign up to request clarification or add additional context in comments.

Comments

2

I would whitelist rather than blacklist the characters you want:

string.replace(/[^\w[\] ]/g, '');

2 Comments

This will leave underscores if present in input.
@anubhava good point; if that's undesired then using the a-z\d will work with i, or [^\p{Letter}\p{Number} [\]] if unicode property escapes are available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.