現在のサイトの URL パスを取得する方法はありますが、最後のセグメントはありません。
http://www.domain.com/first/second/last
必要なのはhttp://www.domain.com/first/second
... jQuery (または JavaScript のみ) のみ
現在のサイトの URL パスを取得する方法はありますが、最後のセグメントはありません。
http://www.domain.com/first/second/last
必要なのはhttp://www.domain.com/first/second
... jQuery (または JavaScript のみ) のみ
pop と URL API の使用
これは、URL が変更される可能性が低いことを前提としています
document.URLが推奨されているため、使用します
const url = new URL("https://www.example.com/first/second/last"); // new URL(document.URL)
let path = url.pathname.split("/");
path.pop(); // remove the last
url.pathname = path.join("/")
console.log(url)
古い回答: OP の要求に応じて - コメントからの変更あり
const url = "http://www.example.com/first/second/last", // document.URL,
shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)
ここに代替案があります
const url = new URL("http://www.example.com/first/second/last"),
shortUrl = `${url.protocol}//${url.hostname}${url.pathname.slice(0,url.pathname.lastIndexOf("/"))}`
console.log(shortUrl)
すべてのブラウザで次のことを試してください。
var url = "http://www.domain.com/first/second/last"; // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))
alert(subUrl);
このlastIndexOf()
メソッドは、文字列内で指定された値が最後に出現した位置を返します。
注: 文字列は末尾から先頭に向かって検索されますが、先頭 (位置 0) から始まるインデックスが返されます。
検索する値が存在しない場合、このメソッドは -1 を返します。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf
これを試して:
var url = 'http://www.domain.com/first/second/last';
for(var i=url.length-1; i>=0;i--){
if(url[i]!='/'){
url= url.substr(0,i);
}
else{
alert(url);
break;
}
}
これが最も洗練されたソリューションかどうかはわかりませんが、最後の文字がスラッシュの場合は最後のスラッシュまで、または最後から 2 番目の部分文字列が必要なだけです。ここではまず、プロトコル (http:// または https://) の後に表示される URL の一部を取得して、たとえばhttp://stackoverflow.comでhttp://stackoverflow.comを返すようにします。
var url = document.URL.split('://');
var last_slash;
var result;
if (url[1].charAt(url[1].length - 1) === '/') {
url[1] = url[1].substring(0, url[1].length - 1);
}
last_slash = url[1].lastIndexOf('/');
result = url[0] + '://' + ((last_slash !== -1) ? url[1].substring(0, last_slash) : url[1]);
編集:jsfiddle http://jsfiddle.net/CV6d4/