-10

What RegEx can I use to parse a string so that it accepts only integers and the / character?

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
user2493287
  • 255
  • 1
  • 4
  • 16

1 Answers1

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
  • why not `var regex = /^[0-9/]+$/;`? – Martin Ender Jul 16 '13 at 10:11
  • I'm just used to write it that way. Shouldn't be a difference though, right? – eyecatchUp Jul 16 '13 at 10:13
  • Btw, you could also write the regex as `/^[\d\/]+$/`. – eyecatchUp Jul 16 '13 at 10:18
  • 1
    I 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