Mary
Mary

Reputation: 1145

In JavaScript, how do I change my regular expression to match all non-alphanumeric characters?

My code is as follows:

"File name) - Title".match("[^ a-zA-Z\d\s:]")

At the moment, it matches ")" but I want it to match ") -", being the non alpha-numeric non-space characters between 'File name' and 'Title'

How do I change my regex to do this?

Upvotes: 0

Views: 84

Answers (2)

James Wakefield
James Wakefield

Reputation: 526

/\s*(?:[^a-zA-Z\d\s:]\s*)+/

This regular expression matches optional leading spaces that are followed by one or more groups of non alphanumeric characters and optional trailing spaces. The question mark just means that what is captured within the round brackets is not saved as special component

Upvotes: 0

wang
wang

Reputation: 1780

If you want to match ")" and "-" separately, use g flag

"File name) - Title".match(/[^ a-zA-Z\d\s:]/g)

If you want to match ") -" which is non-alphanumeric+space+non-alphanumeric,

"File name) - Title".match(/[^ a-zA-Z\d\s:]( )*[^ a-zA-Z\d\s:]/g)

Upvotes: 2

Related Questions