Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

you could also do something like:

url.split('pokemon/')[1].split('/')[0]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda