0

I am trying to do something fairly simple however I have not worked extensively with Regex before.

I am trying to extract some strings out of another string.

I have the string 'value/:id/:foo/:bar'

I would like to extract each string after the colon and before slash eg:

let s = 'value/:id/:foo/:bar';
let r = new RegExp(/MAGIC HERE/);
// result r.exec(s)

I have been trying for an hour or so on this website: https://regex101.com/ but can only get as close as this:

:([a-z]+)

I also tried playing with these examples but couldn't get anywhere:

Regex match everything after question mark?

How do you access the matched groups in a JavaScript regular expression?

I want to be able to extract these parameters infinitely if possible.

My intended result is to get an array of each of the parameters.

group 1 - id
group 2 - foo
group 3 - bar

Please consider explaining the regex that can help with this I want to understand how groups are formed in the regex.

Daniel Tate
  • 2,075
  • 4
  • 24
  • 50
  • `'value/:id/:foo/:bar'.match(/:[a-z]+/g)` is this what you're after? – Isaac Feb 13 '18 at 03:56
  • @Isaac Yes! Thanks for the hint. I should have been testing my string against the regex not the other way around! – Daniel Tate Feb 13 '18 at 04:03
  • Yea that'd do it. Should be fairly simple to extend to using numbers, capitals, underscores, etc. Sometimes it just takes a fresh mind to look at the problem eh? – Isaac Feb 13 '18 at 04:04

3 Answers3

1
'value/:id/:foo/:bar'.match(/:[a-z]+/g)

Returns

[":id", ":foo", ":bar"]
Isaac
  • 11,409
  • 5
  • 33
  • 45
0

try this:

 let reg=/:(.*?)\/|:(.*?)$/g;
 let reg2=/:(.*?)\/|:(.*?)$/;
 let str='value/:id/:foo/:bar';
 let result=str.match(reg).map(v=>v.match(reg2)[1]?v.match(reg2)[1]:v.match(reg2)[2]);

 console.log(result);
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0

"/:" This regex , don't try to match the text between separators, but the separator '/:'.

I hope this help...

let s = 'value/:id/:foo/:bar';
s = s.split("\/\:").splice(1).map((current, index) => `group ${index+1}: - ${current}`);
console.log(s);
Lex
  • 3
  • 1
  • 1