RegEx does not match string in production, however works on tester
I have the following line: /v0/lifts/0626df905120f6d6/refs/8f23576e6838b528
. I'm trying to get a third of the URL string, so I wrote the following a RegEx: /([^/]*)\w+/g
. According to Regexr, this should match all parts of the URL .
Then, with Javascript, I tried to access the element of the third array:
var key = /([^/]*)\w+/g.exec('/v0/lifts/0626df905120f6d6/refs/8f23576e6838b528')[2];
However, it happens to be undefined. If you print the result (as JSON) you get ["v0","v"]
.
Any ideas what's wrong?
source to share
The first thing wrong is using the wrong tool for the job.
Just split by /
, you don't need regexes.
'/v0/lifts/0626df905120f6d6/refs/8f23576e6838b528'.split('/')[3]; //0626df905120f6d6
Now, if you want to use a regular expression, use match
instead:
'/v0/lifts/0626df905120f6d6/refs/8f23576e6838b528'.match(/([^/]*)\w+/g) //["v0", "lifts", "0626df905120f6d6", "refs", "8f23576e6838b528"]
exec
useful only when you have multiple capture groups per match.
source to share