Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

you could also do something like:

url.split('pokemon/')[1].split('/')[0]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda