What RegEx can I use to parse a string so that it accepts only integers and the /
character?
Asked
Active
Viewed 129 times
-10

Aryan Beezadhur
- 4,503
- 4
- 21
- 42

user2493287
- 255
- 1
- 4
- 16
-
3You should have tried something before asking a *quick reply*. – sp00m Jul 16 '13 at 10:05
-
3What have you tried already? StackOverflow is here to help you, not write your code for you. – Adrian Wragg Jul 16 '13 at 10:05
-
A previous post partially solves your problem hope it helps http://stackoverflow.com/questions/9043551/regex-match-integer-only – AurA Jul 16 '13 at 10:07
1 Answers
2
var a = '123/4';
var b = 'e123/4';
Variant 1
var regex = new RegExp('^[0-9/]+$');
console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false
Variant 2
var regex = /^[0-9/]+$/;
console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false
Variant 3
var regex = /^[\d\/]+$/;
console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false

eyecatchUp
- 10,032
- 4
- 55
- 65
-
-
I'm just used to write it that way. Shouldn't be a difference though, right? – eyecatchUp Jul 16 '13 at 10:13
-
-
1I think using the constructor should be slightly less efficient, because you need to create a string object and have the overhead of another function call. Plus, the syntax gets a lot more ugly, when you use escapes (because you need to double all backslashes). I'd only use the constructor for dynamically created (concatenated) patterns. – Martin Ender Jul 16 '13 at 10:27