如何使用 jquery 提取 URL 参数

How to extract URL parameters with jquery

本文关键字:URL 参数 提取 jquery 何使用      更新时间:2023-09-26

我有一些这样的链接:

mywebsite.com/tutos.php?name=tuto_name#comments
mywebsite.com/tutos.php?name=tuto_name#download

我的问题:如何获取#之后的文本。

谢谢。

window.location.hash 是一个跨浏览器解决方案,返回值(包括哈希)

您可以通过执行以下操作来删除哈希:

var hash = window.location.hash.substr(1);

我使用以下方法,因为它不仅获取hash值(没有哈希本身(取第二部分(splitarray[1])),而且还测试了在某些情况下可能导致问题的undefined情况。

var hashVal = window.location.hash.split("#")[1];
if( hashVal && hashVal != "undefined" ) {
       //work it 
 }

我使用以下JS函数来执行此操作:

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search) || [, ""])[1].replace(/'+/g, '%20')) || null
}
您可以使用

window.location.hash .它需要#(即#comments)。要删除试用#请使用.substring(1) 。例:

var str = window.location.hash.substring(1);
alert(str);