Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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]);

about 4 years ago · Juan Pablo Isaza Report

0

you could also do something like:

url.split('pokemon/')[1].split('/')[0]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!