5

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!

5
  • Firstly look at this question, it maybe helpfull for you stackoverflow.com/questions/15534673/… is it? Commented Mar 21, 2013 at 2:34
  • 1
    is it specifically for the url only, or do you intend to use the function generically... as in, what if you just remove the "/Books/The-Happy-donkey" part? Commented Mar 21, 2013 at 2:35
  • The "/Books/The-Happy-donkey" is dynamic, so the only reference i have is the .aspx part, but with split is doing no good Commented Mar 21, 2013 at 2:38
  • @GlenSwift actually no... I need the whole page until .aspx so i can connect into a webMethod :( Commented Mar 21, 2013 at 2:40
  • Hi, I'm finding it hard to understand your question, would you mind adding more inputs with expected output? It's hard to induce from a single example with this description. Commented Mar 21, 2013 at 2:42

5 Answers 5

4

Try this

var fullurl = "http://www.store.com/products.aspx/Books/The-happy-donkey",
    url = fullurl.split(".aspx")[0] + ".aspx";
Sign up to request clarification or add additional context in comments.

1 Comment

Smart and effective
4

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

Comments

3

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('/')

Comments

1

The better answer (than split) is probably with a regex honestly unless you just REALLY need to use split (for the fun of it):

var shorterUrl = window.location.href.replace(/\.aspx.+/gi, ".aspx");

this replaces the end of your given url, starting at .aspx and just keeps the .aspx part.

But foremost, this is not a good solution tactic to a specific problem (try to solve problems like this more generically).

Comments

0

try this, you would get object of url

console.log(new URL(document.URL));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.