Store URL snippet - Javascript

Asked

Viewed 483 times

1

I am capturing a certain value of the URL through Javascript, but I’m having difficulty at some point. Follow 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 http://google.com/pagina.current, when executing the above code the return will be given "page.current". No news.

However, when I add parameters beyond the "current page", eg: "http://google.com/pagina.atual?origem=teste", it will capture the "current page? origin=test". I need ONLY the "current page.".

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

  • You can use a split even "pagina.atual?origem=teste".split('?')[0]

  • Kaleb, some of the answers solved your question?

  • Sergio, yes. Pedro Camara’s comment right after the question was posted helped a lot. I didn’t answer before for the rush.

3 answers

1


Try it this way:

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 take 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]);

1

There are several ways.

You can do it 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 that with Scotch:

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

You can do it with split:

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

1

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

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

Example : JSFIDDLE EXAMPLE

Browser other questions tagged

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