NSjonas
NSjonas

Reputation: 12032

Javascript Regular expression capture

I'm sure there might be something simular on stack overflow but I can't find anything and am getting quite frustrated with what should be very simple.

I need to capture part of a url (similar to a url rewriting engine) using javascript.

URL structure:

http://example.com/constant/CAPTURETHIS

http://example.com/constant/CAPTURETHIS/

http://example.com/constant/CAPTURETHIS#noise

http://example.com/constant/CAPTURETHIS/#noise

I need to just return the CAPTURETHIS text for all 3 senerios

Upvotes: 1

Views: 501

Answers (1)

ruakh
ruakh

Reputation: 183321

JavaScript supports the retrieval of regex capture-groups by using a string object's match method or a regular-expression object's exec method:

var captureThis = url.match(/^http:[/][/]example[.]com[/]constant[/]([^/]+)/)[1];
var captureThis = /^http:[/][/]example[.]com[/]constant[/]([^/]+)/.exec(url)[1];

But for your example, I almost wonder if it's simpler to use the string object's split method:

var captureThis = url.split(/[/]/)[4];

Upvotes: 5

Related Questions