Extract values from a string in javascript [duplicate]

-3

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

  

/ Material / Index ?? wordChave ?? numPage

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

  

/ Material / Index? qw = WordChave & pag = numPage

How do I save a keywordChave and another numPage in a variable and most importantly: the keyword may be missing, but have the page number. With the question marks I have I can not tell if what I have in URL is a search value, or a page.

    
asked by anonymous 16.01.2017 / 14:27

2 answers

1

As you work with a small string and have a pattern. you can try to use regex.

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

Where in parentheses are the groups that are important to you.

example of your case

    
16.01.2017 / 14:52
1

You can use location.search that will return from ? to the end of the URL. Then treat the result.

Example for your case:

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

Simulation of treatment:

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);
    
16.01.2017 / 14:35