Extract values from a javascript string

Asked

Viewed 382 times

-3

I have a page that presents information through AJAX. Each time I do a search, I have the value of the search and page on URL, as follows:

/Material/Index?? palavraChave?? numPagina

I can trace those values through .split("??"), but wanted to implement something more intuitive:

/Material/Index? qw=palavraChave&pag=numPagina

How do I save to a single variable a cuss and another to in a magazine and most importantly: the keyword may be missing, but have the page number. With the question marks I have I can’t tell if what I have on URL is a search value, or a page.

  • How is your ajax to create this Url?

  • I do not use ajax to create the url, I am using pushState() and pass the variables that the user enters into a search box,

2 answers

1

You can use Location.search who will return from ? to the end of the URL. Then process the result.

Example for your case:

var url = window.location.search; // retorno será algo como: '?qw=palavraChave&pag=numPagin';
var campos = url.split('=');

Treatment simulation:

var url = window.location.search; // retorno será algo como: '?qw=palavraChave&pag=numPagin';
var resExamplo = '?qw=stackoverflow&pag=10';
var campos = resExamplo.split('=')[2]; // obter o numero da pagina
console.log(campos);

  • The problem of this code is similar to mine: if there is no keyword search then it will assume that the page is keyword. I wanted something that "knew" identify each variable.

  • "he will assume that the page is the keyword". There is no magic to get the parameters of a URL, you will need to get the URL somehow and check what is in it. In the treatment example, it is possible to "know" each variable, both the name and the value.

  • I know there is no magic, but I have discovered that there is regex. But with this technique you have put it is possible to "know" which is which in which way?

1


How you work with a small string and have a pattern. can try using regex.

qw=([A-Za-z0-9]+)&pag=([0-9]+)

where what is in parentheses are the groups that are important to you.

example of your case

  • achieved perfectly using this technique, thank you! regex is very good!

Browser other questions tagged

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