Rafa Tost
Rafa Tost

Reputation: 399

regex to match alphanumeric and hyphen only, strip everything else in javascript

I want to strip everything except alphanumeric and hyphens.

so far i've got this but its not working:

String = String.replace(/^[a-zA-Z0-9-_]+$/ig,'');

any help appreciated?

Upvotes: 2

Views: 8331

Answers (1)

thefourtheye
thefourtheye

Reputation: 239693

If you want to remove everything except alphanum, hypen and underscore, then negate the character class, like this

String = String.replace(/[^a-zA-Z0-9-_]+/ig,'');

Also, ^ and $ anchors should not be there.

Apart from that, you have already covered both uppercase and lowercase characters in the character class itself, so i flag is not needed. So, RegEx becomes

String = String.replace(/[^a-zA-Z0-9-_]+/g,'');

There is a special character class, which matches a-zA-Z0-9_, \w. You can make use of it like this

String = String.replace(/[^\w-]+/g,'');

Since \w doesn't cover -, we included that separately.

Quoting from MDN RegExp documentation,

\w

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."

Upvotes: 10

Related Questions