arielcr
arielcr

Reputation: 1663

RegEx to get section of URL after string in Javascript

I have the following URL:

http://data.test.com/api/v1/entity/1231

And I need to get the text that is after v1/ and before / (between the slashes), in this case the word entity. I'm using the following regex, but what I get back is entity/1231 on group 1:

/^[^\#\?]+\/v1\/([^\?]+).*$/

Any idea on how to get rid of 1231 or anything that comes after entity?

Upvotes: 2

Views: 1910

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

You may capture the value you need into a capturing group with new RegExp("/v1/([^/]+)":

var str = "http://data.test.com/api/v1/entity/1231";
var res = str.match(new RegExp("/v1/([^/]+)"));
if (res) 
    console.log(res[1]);

The /v1/([^/]+) matches:

  • /v1/ - a literal string /v1/
  • ([^/]+) - capturing group 1 matching one or more chars other than /.

Thanks to the constructor notation in the RegExp definition, there is no need to escape forward slashes in the regex pattern.

Alternatively, since ECMAScript 2018 enabled lookbehind usage in the JavaScript RegExp patterns, you can also use a lookbehind-based approach to get the value you need directly as a whole match:

const str = "http://data.test.com/api/v1/entity/1231";
const res = str.match(/(?<=\/v1\/)[^\/]+/);
if (res) {
    console.log(res[0]);
}

Details:

  • (?<=\/v1\/) - a positive lookbehind that matches a location that is immediately preceded with /v1/ text
  • [^\/]+ - one or more chars other than a / char.

Upvotes: 6

Waqas
Waqas

Reputation: 171

try this:

^[^\#\?]+\/v1\/([^\?]+).*(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/1231)$

Upvotes: 3

Related Questions