0

I've been trying to compose a regex for a partial url path. The path looks something like:

/stoic/variable/important/

By "stoic" I mean that part is stoic and has the same letters that won't change. By "variable" I mean that part is dynamic and will change dependent on some stuff, and should be an alphanumeric combination. By "important" I mean a part that is just composed of letters that I want to capture precisely.

I've tried the following to no avail:

/^(/stoic/\w+\/important/)$/.test(someString)
nmac
  • 610
  • 1
  • 10
  • 20
  • 1
    `/stoic/\w+\/important/` escape all `/` here – Cheery Nov 26 '14 at 20:22
  • possible duplicate of [Matching a Forward Slash with a regex](http://stackoverflow.com/questions/16657152/matching-a-forward-slash-with-a-regex) – Andrew Morton Nov 26 '14 at 20:28
  • yeah I forgot to escape the /, for any future reference, the solution is: `/^(\/stoic\/\w+\/important\/)$/` – nmac Nov 26 '14 at 20:35

1 Answers1

0

As an alternative to escaping all the slashes, you can also use the RegExp constructor:

RegExp('^(/stoic/\\w+/important/)$').test('/stoic/foobar/important/')
// => true

Note that you need to use two backslashes for the character classes then, as single backslashes will only trigger the string escapes such as '\n'.

Luchs
  • 1,133
  • 1
  • 9
  • 10