如果您不想为其创建新元素或依赖a.pathname
,我建议使用indexOf
and slice
。
function getPath(s) {
var i = s.indexOf('://') + 3, j;
i = s.indexOf('/',i) + 1; // find first / (ie. after .com) and start at the next char
if( i === 0 ) return '';
j = s.indexOf('?',i); // find first ? after first / (as before doesn't matter anyway)
if( j == -1 ) j = s.length; // if no ?, use until end of string
while( s[j-1] === '/' ) j = j - 1; // get rid of ending /s
return s.slice(i, j); // return what we've ended up at
}
getPath(document.referrer);
如果你想要正则表达式,也许这个
document.referrer.match(/:\/\/[^\/]+[\/]+([^\?]*)[\/]*(?:\?.*)?$/)[1]
它确实“找到第一个://
,继续直到下一个/
,然后获取不是?
直到 a?
或字符串的最后一个/
或结尾的所有内容并捕获它”,这与我上面所做的功能基本相同。