'Clean way to get value from string in Javascript

I have this string https://pokeapi.co/api/v2/pokemon/6/

I would like to extract the value after pokemon/ in this case 6. This represent Pokémon ids which could span between 1 -> N

I know this is pretty trivial and was wondering a nice solution for future proofing. Here is my solution.

const foo= "https://pokeapi.co/api/v2/pokemon/6/"
const result = foo.split('/') //[ 'https:', '', 'pokeapi.co', 'api', 'v2', 'pokemon', '6', '' ]
const ids = result[6]


Solution 1:[1]

You can grab the value after the last / character like so:

const pokemonID = foo.substring(foo.lastIndexOf("/") + 1)

Using String.lastIndexOf to get the final index of the slash character, and then using String.substring with only a single argument to parse the part of the string after that last / character. We add 1 to the lastIndexOf to omit the final slash.

For this to work you need to drop your final trailing slash (which won't do anything anyways) from your request URL.

This could be abstracted into a utility function to get the last value of any url, which is the biggest improvement over using a split and find by index approach.

However, beware, it will take whatever the value is after the last slash. Using the string https://pokeapi.co/api/v2/pokemon/6/pokedex would return pokedex.

If you are using Angular, React, Vue etc with built in router, there will be specific APIs for the framework that can get the exact parameter you need regardless of URL shape.

Solution 2:[2]

You should use the built-in URL API to do the splitting correctly for you:

const url = new URL("https://pokeapi.co/api/v2/pokemon/6/");

Then you can get the pathname and split that:

const path = url.pathname.split("/");

After you split it you can get the value 6 by accessing the 5th element here:

const url = new URL("https://pokeapi.co/api/v2/pokemon/6/");

const path = url.pathname.split("/");

console.log(path[4]);

Solution 3:[3]

you could also do something like:

url.split('pokemon/')[1].split('/')[0]

Solution 4:[4]

Here is what I would do

const result = new URL(url).pathname.split('/');
const id = result[4];

Solution 5:[5]

I am not sure if this is better than yours

const foo= "https://pokeapi.co/api/v2/pokemon/6/"
const result = foo.indexOf("pokemon/");
const id_index = result + 8
const id = foo[id_index]; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Specker
Solution 2
Solution 3 Medda86
Solution 4 Freddy.
Solution 5 K.D