Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern to get number between forward slashes at the end of a URL

Tags:

regex

I have a string URL that I just want to grab the number at the very end between "pokemon/" and "/".

"http://pokeapi.co/api/v2/pokemon/1/"

so far I have this -

var regexPat = /\/d+\//
"http://pokeapi.co/api/v2/pokemon/1/".match(regexPat)[0].slice(1,2) // returns 1

Is there a more efficient way to do this?

like image 649
mangocaptain Avatar asked Oct 17 '25 07:10

mangocaptain


1 Answers

You may capture the value with a /\/pokemon\/(\d+)\// regex:

var s = "http://pokeapi.co/api/v2/pokemon/1/";
var m = s.match(/\/pokemon\/(\d+)\//);
if (m) {
  console.log(m[1]);
}
// or 
console.log( 
  (res="http://pokeapi.co/api/v2/pokemon/1/".match(/\/pokemon\/(\d+)\//)) ? res[1] : ""
);

Details:

  • \/pokemon\/ - a literal text /pokemon/
  • (\d+) - Capture group 1 matching 1 or more digits
  • \/ - a / symbol.
like image 166
Wiktor Stribiżew Avatar answered Oct 19 '25 22:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!