簡體   English   中英

如何獲取當前 URL 的一部分?

[英]How to get part of URL current?

我的網址看起來像: http : //google.com/stackoverflow/post/1

現在,我只想獲取 URL 的一部分: http : //google.com/stackoverflow/並將其添加到代碼中:

郵政 。 怎么做 ? 謝謝 !

請試試這個:

var url = "http://google.com/stackoverflow/post/1";
var partOfUrl = url.split('post')[0];

謝謝。

使用位置對象

location.href
location.pathname

更新:

使用 JavaScript:

var url = "http://google.com/stackoverflow/post/1";    // or var url = window.location;

var matches = url.match(/^http\:\/\/([\w\.]+)\/(\w+)\/.+/);

if( matches ){
    var newURL = "http://" + matches[1] + "/" + matches[2] + "/";
    alert( newURL );
}

document.getElementById('post_link').href = newURL;

HTML:

<a id="post_link">post</a>

JSFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM