【问题标题】:Regular expression to find and replace specific value from a URL从 URL 中查找和替换特定值的正则表达式
【发布时间】:2013-11-20 05:24:51
【问题描述】:
【问题讨论】:
标签:
javascript
jquery
regex
expression
【解决方案1】:
您发布的示例的解决方案。
str = str.replace(/\b(ref=)[^&?]*/i, '$1testing');
正则表达式:
\b the boundary between a word char (\w) and and not a word char
( group and capture to \1:
ref= 'ref='
) end of \1
[^&?]* any character except: '&', '?' (0 or more times)
i 修饰符用于不区分大小写的匹配。
见working demo
【解决方案2】:
确保您没有两个“?”在网址中。我假设你的意思是
http://myexample.com?ref=test&nref=xml&page=1
你可以使用下面的函数
这里 url 是你的 url,name 是键,在你的例子中是“ref”,new_value 是新值,即替换“test”的值
函数将返回新的 url
function replaceURLParam (url, name, new_value) {
// ? or &, name=, anything that is not &, zero or more times
var str_exp = "[\?&]" + name + "=[^&]{0,}";
var reExp = new RegExp (str_exp, "");
if (reExp.exec (url) == null) { // parameter not found
var q_or_a = (url.indexOf ("?") == -1) ? "?" : "&"; // ? or &, if url has ?, use &
return url + q_or_a + name + "=" + new_value;
}
var found_string = reExp.exec (url) [0];
// found_string.substring (0, 1) is ? or &
return url.replace (reExp, found_string.substring (0, 1) + name + "=" + new_value);
}
【解决方案3】:
试试这个:
var name = 'ref',
value = 'testing',
url;
url = location.href.replace(
new RegExp('(\\?|&)(' + name + '=)[^&]*'),
'$1$2' + value
);
new RegExp('(\\?|&)(' + name + '=)[^&]*') 给出/(\?|&)(ref=)[^&]*/ 这意味着:
"?" or "&" then "ref=" then "everything but '&' zero or more times".
最后,$1 持有(\?|&) 的结果,而$2 持有(ref=) 的结果。
阅读链接:replace、regexp。