Industrial
Industrial

Reputation: 42778

Filtering out 0-9 & dashes only?

I would like to create a regexp that targets any characters in my string that isn't 0-9 (numeric) or - (dash). What is wrong with my below regexp?

Regex:

regex = '/^[0-9-]/g';

JS implementation:

$(this).val($(this).val().replace(regex, ''));

Upvotes: 1

Views: 208

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

I think you meant for your ^ to be inside the character class. Also, regexes are not strings:

regex = /[^0-9-]/g;
$(this).val($(this).val().replace(regex, ''));

Upvotes: 4

Aleks G
Aleks G

Reputation: 57316

You need to put '^' inside the brackets and escape '-', it being a special char. Your regex should be

regex = /[^0-9\-]/g

Upvotes: 0

Related Questions