Filter two values in a text type variable

Asked

Viewed 72 times

0

I want to take these two values that are found in the following variable:

let url = "https://localhost:44380/Manga/MangaPaginas/?idManga=1&idCapitulo=2";

What I want is the idManga and idCapitulo;

I am using javascript and want to generate two variables with the same names.

  • Do you want to pick up where? No backend? No frontend? How are these values coming?

  • i’m already picking up this value, I want to filter by javascript.

  • this Odigo is running on the html page

  • this string is fixed, I just need to extract the two numbers

2 answers

1


If input is a url and the goal is to read the query parameters use the interface URL for the analysis.

The estate Searchparams access the query parameters individually.

var url = new URL("https://localhost:44380/Manga/MangaPaginas/?idManga=1&idCapitulo=2");

console.log("idManga = " + url.searchParams.get("idManga"));
console.log("idCapitulo = " + url.searchParams.get("idCapitulo"));

If the goal is to list the query parameters and values of a url. Itere com for of about SearchParams.

var url = new URL("https://localhost:44380/Manga/MangaPaginas/?idManga=1&idCapitulo=2");

for (const [key, value] of url.searchParams) {
  console.log(key + " = " + value);
}

  • vlw man, that’s just what I wanted

0

You can do this in a very simple way, using a regular expression to pick up the two numbers from the last bar /, the first number being the value of "idManga" and the second the value of "idCapitulo".

Using url.substr(url.lastIndexOf("/")) will return everything you have from the last bar forward, ie:

/?idManga=1&idCapitulo=2

Then just use a .match() with the regular expression /\d+/g which will return an array with the two values:

["1", "2"]

The expression /\d+/g takes anything that is number in the string, creating the array by separating the values in each index, where the index [0] is the value of "idManga" and the index [1] the value of "idCapitulo".

See how it looks:

let url = "https://localhost:44380/Manga/MangaPaginas/?idManga=10&idCapitulo=21";
const valores = url.substr(url.lastIndexOf("/")).match(/\d+/g);
console.log("idManga = ", valores[0]);
console.log("idCapitulo = ", valores[1]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.