2

I have the following URL structure:

https://api.bestschool.com/student/1102003120009/tests/json

I want to cut the student ID from the URL. So far I've came up with this:

/(student\/.*[^\/]*)/

which returns

student/1102003120009/tests/json

I only want the ID.

1 Answer 1

4

Your regex (student\/.*[^\/]*) matches and captures into Group 1 a literal sequence student/, then matches any characters other than a newline, 0 or more occurrences (.*) - that can match the whole line at once! - and then 0 or more characters other than /. It does not work because of .*. Also, a capturing group should be moved to the [^\/]* pattern.

You can use the following regex and grab Group 1 value:

student\/([^\/]*)

See regex demo

The regex matches student/ literally, and then matches and captures into Group 1 zero or more symbols other than /.

Alternatively, if you want to avoid using capturing, and assuming that the ID is always numeric and is followed by /tests/, you can use the following regex:

\d+(?=\/tests\/)

The \d+ matches 1 or more digits, and (?=\/tests\/) checks if right after the digits there is a /tests/ character sequence.

var re = /student\/([^\/]*)/; 
var str = 'https://api.bestschool.com/student/1102003120009/tests/json';
var m = str.match(re);
if (m !== null) {
   document.getElementById("r").innerHTML = "First method&nbsp;&nbsp;&nbsp;&nbsp;: " + m[1] + "<br/>";
}
var m2 = str.match(/\d+(?=\/tests\/)/);
if (m2 !== null) {
    document.getElementById("r").innerHTML += "Second method: " + m2;
}
<div id="r"/>

Sign up to request clarification or add additional context in comments.

6 Comments

I must ask, why is it adding it to array? Can't it retrieve only the ID? there is only one thing between "student/" and "/test"
It all depends on the context the ID appears in. If you need it to be right between student/ and /test, you need to use a capturing group with /sudent\/([^\/]*)\/test/ - and the captured value is inside the m[1]. See RegExp#match reference. If you just need to get the numeric value before /test, you can get the match itself with str.match(/\d+(?=\/test)/). As you see, everything depends on what part of the string we can use as context (=known details we can use a literal in the regex).
Is it possible to add a condition to the regex? "student/" sometimes can be "studentid/" , i want to cover both cases with same regex - possible?
Yes, possible. Use \w* that matches 0 or more alphanumeric symbols: var re = /student\w*\/([^\/]*)/;
I'm not quite how to do this, all my attempts failed
|

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.