Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split url with JavaScript

Tags:

javascript

I'm trying to split the following url:

http://www.store.com/products.aspx/Books/The-happy-donkey

in order to get only http://www.store.com/products.aspx

I'm using JavaScript window.location.href and split but not success so far.

How can this be done? thanks!

like image 594
Arturo Suarez Avatar asked Mar 21 '13 02:03

Arturo Suarez


People also ask

How to split a URL in JavaScript?

var newURL="http://www.example.com/index.html/homePage/aboutus/"; console. log(newURL); var splitURL=newURL. toString(). split("/"); console.

How do you break down a URL?

What are the parts of a URL? A URL consists of five parts: the scheme, subdomain, top-level domain, second-level domain, and subdirectory.

How do you split a URL in Python?

Method #1 : Using split() This is one of the way in which we can solve this problem. We split by '? ' and return the first part of split for result.


3 Answers

Try this

var fullurl = "http://www.store.com/products.aspx/Books/The-happy-donkey",
    url = fullurl.split(".aspx")[0] + ".aspx";
like image 87
Sasidhar Vanga Avatar answered Oct 11 '22 14:10

Sasidhar Vanga


In the case of a url: http://www.store.com/products.aspx/Books/The-happy-donkey from the address bar

 var path = window.location.pathname;
 var str = path.split("/");
 var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1];
like image 40
Daniel Avatar answered Oct 11 '22 13:10

Daniel


This isn't unwieldy, is it?

var url = 'http://www.store.com/products.aspx/Books/The-happy-donkey';

[
    url.split('://')[0] + '://', 
    url.split('://')[1].split('/').slice(0,2).join('/')
].join('')

A little less cheeky:

url.split('/').slice(0, 4).join('/')
like image 23
Jared Farrish Avatar answered Oct 11 '22 13:10

Jared Farrish