2

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?

5
  • 1
    v1\/([^/]+) or v1\/(.*?)\/ Commented Mar 29, 2017 at 16:27
  • If the parts are fixed "http://data.test.com/api/v1/entity/1231".split("/")[5] Commented Mar 29, 2017 at 16:27
  • If the URLs you're working with are that predictable then regular expressions, while possible, may be an overly-complex tool for the job. Are the URLs changeable? Will it always be "after v1/ and before [the next] /"? Commented Mar 29, 2017 at 16:28
  • @DavidThomas Yes, they are predictable Commented Mar 29, 2017 at 16:33
  • You need str.match(/\/v1\/([^\/]+)/)[1] Commented Mar 29, 2017 at 16:33

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

Comments

3

try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.