views:

194

answers:

4

Hey all.

Thanks in advance.

I would like a regular expression that removes anything that is NOT alpha numeric and a hyphen. So allowed are A-Z 0-9 and -.

Also, how could I apply that to a string in Javascript?

Thanks again.

+3  A: 
var str = 'a23a-asd!@#$';
str.replace(/[^-a-z0-9]/ig,'');
Anatoliy
'a23a-asd'.replace(/[^-a-z \d]/ig,''); (forgot the \d) :D
CrazyJugglerDrummer
+1  A: 

Try this:

str = str.replace(/[a-zA-Z\d-]/g, "");
Andrew Hare
You mean `[^\w\d-]`.
Gumbo
No, `\w` includes underscores which the OP didn't ask for.
Andrew Hare
@Andrew Hare: But you first had `[\w\d-]`.
Gumbo
Ah true - good point.
Andrew Hare
A: 
var output = input.replace(/[^A-Za-z0-9-]/g, "");
Marius
you need the **g**lobal flag on that otherwise it just replaces the first match.
nickf
Thanks, fixed :)
Marius
A: 

string.replace(/[^a-zA-Z0-9-]/g, "");