所以我想替换 url 中的 GET 变量值,如果该变量不存在,则将其添加到 url。
编辑:我正在对元素 href 而不是页面当前位置执行此操作。
我不擅长 javascript,但我知道如何很好地使用 jQuery 和 javascript 的基础知识。我确实知道如何编写正则表达式,但不知道如何使用正则表达式的 javascript 语法以及将其与哪些函数一起使用。
这是我到目前为止的内容,它在第 3 行确实有错误:在 jsfiddle(或以下)上查看:http://jsfiddle.net/MadLittleMods/C93mD/
function addParameter(url, param, value) {
var pattern = new RegExp(param + '=(.*?);', 'gi');
return url.replace(pattern, param + '=' + value + ';');
alert(url);
}
最佳答案
不需要在这个上使用 jQuery。正则表达式和字符串函数就足够了。请参阅下面我的注释代码:
function addParameter(url, param, value) {
// Using a positive lookahead (?=\=) to find the
// given parameter, preceded by a ? or &, and followed
// by a = with a value after than (using a non-greedy selector)
// and then followed by a & or the end of the string
var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
parts = url.toString().split('#'),
url = parts[0],
hash = parts[1]
qstring = /\?.+$/,
newURL = url;
// Check if the parameter exists
if (val.test(url))
{
// if it does, replace it, using the captured group
// to determine & or ? at the beginning
newURL = url.replace(val, '$1' + param + '=' + value);
}
else if (qstring.test(url))
{
// otherwise, if there is a query string at all
// add the param to the end of it
newURL = url + '&' + param + '=' + value;
}
else
{
// if there's no query string, add one
newURL = url + '?' + param + '=' + value;
}
if (hash)
{
newURL += '#' + hash;
}
return newURL;
}
这里是 the Fiddle
更新:
代码现在处理 URL 上有散列的情况。
编辑
错过了一个案例!代码现在检查是否存在查询字符串。
关于javascript - 使用 javascript 在 url 中添加/修改查询字符串/GET 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640270/