最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Split url with JavaScript - Stack Overflow

programmeradmin3浏览0评论

I'm trying to split the following url:

.aspx/Books/The-happy-donkey

in order to get only .aspx

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

How can this be done? thanks!

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!

Share Improve this question edited Jul 30, 2020 at 14:33 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Mar 21, 2013 at 2:31 Arturo SuarezArturo Suarez 6653 gold badges10 silver badges16 bronze badges 5
  • Firstly look at this question, it maybe helpfull for you stackoverflow.com/questions/15534673/… is it? – Boris Zagoruiko 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? – Ryan 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 – Arturo Suarez Commented Mar 21, 2013 at 2:38
  • @GlenSwift actually no... I need the whole page until .aspx so i can connect into a webMethod :( – Arturo Suarez 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. – Benjamin Gruenbaum Commented Mar 21, 2013 at 2:42
Add a comment  | 

5 Answers 5

Reset to default 4

Try this

var fullurl = "http://www.store.com/products.aspx/Books/The-happy-donkey",
    url = fullurl.split(".aspx")[0] + ".aspx";

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

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

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).

try this, you would get object of url

console.log(new URL(document.URL));
发布评论

评论列表(0)

  1. 暂无评论