Store URL snippet - JavaScript

1

I'm capturing a certain URL value through JavaScript, but I'm having difficulty at any given time. Follow the steps below.

    var url  = window.location.href;
    var page = url.split('/');
    var page = page[page.length-1];

    var arrayItens = new Array();

Considering, for example, that the URL is link , when executing the above code the return will be given "current page". No news.

However, when I add parameters beyond the "current page", eg " link ", it will capture the "current.page? source = test". I need ONLY the "current page".

Does anyone know how I can do this by following the above passage?

    
asked by anonymous 02.06.2017 / 21:22

3 answers

1

Try this:

var url  = "http://google.com/pagina.atual?origem=teste";
var page = url.split('/');
page = page[page.length-1];

console.log(page.split('?')[0]);

If you want to get the parameters:

var url  = "http://google.com/pagina.atual?origem=teste";
var page = url.split('/');
page = page[page.length-1];

console.log(page.split('?')[1]);
    
02.06.2017 / 21:52
1

There are several ways.

You can do this by regex:

var href = "http://google.com/pagina.atual?origem=teste";
var match = href.match(/([^\/]+)\?/);
var pagina = match && match[1];

console.log(pagina);

You can do this with slice:

var href = "http://google.com/pagina.atual?origem=teste";
var pagina = href.slice(18, href.indexOf('?'));
console.log(pagina);

You can do this with split:

var href = "http://google.com/pagina.atual?origem=teste";
var pagina = href.split('/').pop().split('?').shift();
console.log(pagina);
    
02.06.2017 / 21:52
1

Good morning, I did it in a way that you can easily change the code. I hope it helps!

var url = 'http://google.com/pagina.atual?teste';
url = url.split('/')[3];
if(url.indexOf('?') != -1){
    url = url.split('?')[0];
}
document.write(url);

Example: EXAMPLE JSFIDDLE

    
02.06.2017 / 22:37