0

I've got two related URL matching patterns, one of which works, and the other which works only in regex testers, but not in JS itself.

Pattern 1: match Rails index URL (works)

var pattern = '(?!.*\/items\/.*).*\/items';
var re = new RegExp(pattern);
re.test('/my/items');
=> true

https://regex101.com/r/oO5wJ0/1 (tester matches)
https://jsfiddle.net/x9avvxdc/ (js matches)

Pattern 2: match Rails single resource URL (works in regex tester, not in JS)

var pattern = '(?!.*\/items\/.*\/).*\/items\/\d+';
var re = new RegExp(pattern);
re.test('/my/items/8');
=> false

https://regex101.com/r/bF1rU9/1 (tester matches)
https://jsfiddle.net/k4ownsky/ (js doesn't match)

Not sure what the problem is with number 2...

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • 2
    And [now it works](https://jsfiddle.net/k4ownsky/1/). [*You could replace the line: `var re = /\w+\s/g;` with: `var re = new RegExp("\\w+\\s", "g");` and get the same result.*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). – Wiktor Stribiżew Jan 25 '16 at 20:58
  • @WiktorStribiżew thanks a lot, that did it. From the [answer](http://stackoverflow.com/a/10770718/165673): *"in a regex literal, you also have to put backslashes in front of the forward slashes, since forward slashes are the delimiter for the whole thing"* - but I just didn't realize you weren't allowed to escape forward slashes if it wasn't a literal... – Yarin Jan 25 '16 at 21:18
  • You [can escape them but it is not necessary](https://jsfiddle.net/k4ownsky/2/). – Wiktor Stribiżew Jan 25 '16 at 21:21
  • You're right- was the backslash before the "d" that needed escaping – Yarin Jan 25 '16 at 21:26

0 Answers0