我使用 document.referrer
属性来获取以下 URL:
http://www.site.ru/profile/521590819123/friends
http://www.site.ru/profile/521590819123
http://www.site.ru/profile/521590819123/else
我需要将此字符串中的 ID(例如,如上所示的 521590819123)获取到变量中。这是我到目前为止所拥有的:
<script type="text/javascript">
var ref = document.referrer;
var url = 'http://site.com/?id=';
if( ref.indexOf('profile') >= 0 )
{
ref = ref.substr(ref.lastIndexOf('/') + 1);
window.top.location.href = (url+ref);
}
else
{
window.top.location.href = (url + '22');
}
</script>
但这仅在引用字符串的格式为http://www.site.ru/profile/521590819123
时才有效。上面最后带有 /friends
或 /else
的其他示例将不起作用。有人可以帮我修复代码来处理这些实例吗?
最佳答案
使用正则表达式最简单:
var m, id;
m = /profile\/(\d+)/.exec(document.referrer);
if (m) {
id = m[1];
}
该正则表达式表示“找到文本 profile/
后跟数字的第一个位置,并将数字放入捕获组中。”然后,代码检查是否存在匹配项(如果字符串根本没有匹配项),如果存在,则从第一个捕获组中获取值(位于索引 1;索引 0 是整个匹配字符串) 。根据需要进行修改(例如,仅匹配字符串是 www.site.ru/profile/
而不仅仅是 profile/
等)。
关于Javascript 从引用者中解析 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293218/