0

私が次のいずれかを持っている場合:

example.com/test1
example.com/test1/
example.com/photo/test1
example.com/photo/category/test1/

(要点はわかります)

jqueryのロード時に変数としてtest1を使用するにはどうすればよいですか?

window.location.pathnametest1だけでなく/photo/category/test1/全体を教えてくれます

あなたの時間と助けに感謝します

4

4 に答える 4

0

最後のパス要素を抽出する関数は次のとおりです。

function getLastSegmentOfPath(url) {
    var matches = url.match(/\/([^\/]+)\/?$/);
    if (matches) {
        return matches[1];
    }
    return null;
}

var endPath = getLastSegmentOfPath(window.location.href);

実用的なテストケースとデモ:http://jsfiddle.net/jfriend00/9GXSZ/

正規表現は次のように機能します。

\/  match a forward slash
()  separately capture what is in the parens so we can extract just that part of the match
[^\/]+ match one or more chars that is not a slash
\/?$  match an optional forward slash followed the the end of the string

正規表現の結果(配列):

matches[0] is everything that matches the regex
matches[1] is what is in the first parenthesized group (what we're after here)
于 2012-12-24T22:30:28.080 に答える
0

JavaScriptlastIndexOfsubstr関数を使用できます。

var url = window.location.pathname;
var index = url.lastIndexOf("/");
var lastbit = url.substr(index);

これはURLを取得し、最後の位置を見つけて、この位置/以降のすべてのものを返します。

編集(コメントを参照):末尾のスラッシュ(例:category / test /)を除外するには、最初のスラッシュを使用します。

var url = window.location.pathname;
var index = url.lastIndexOf("/");
var lastbit = url.substr(index);
if (lastbit == "/"){
     url = url.slice(0, - 1); 
     index = url.lastIndexOf("/");
     lastbit = url.substr(index);
}
lastbit = lastbit.substring(1);
于 2012-12-24T22:31:42.187 に答える
0

パス名の最後の部分を見つけたい場合は、次のようなものが機能すると思います。

var path = window.location.pathname.split('/');
path = path.filter(function(x){return x!='';});
var last_path = path[path.length - 1]
于 2012-12-24T22:28:33.727 に答える
0
var parts = "example.com/photo/category/test1/".split('/')
var url = parts[parts.length - 1] ? parts[parts.length - 1] : parts[parts.length - 2];

( が?:最後の を処理します/)

于 2012-12-24T22:28:52.593 に答える