Javascript 用于从URL中查找和替换特定值的正则表达式
我试图从URL中提取?ref值,并希望用其他值替换它 例如,假设我的URL是这样的,也可以是这样的 从上面的url中,我想找到?ref值,并想用另一个字符串替换它,比如“testing”。任何帮助,也希望学习高级正则表达式任何帮助Javascript 用于从URL中查找和替换特定值的正则表达式,javascript,jquery,regex,expression,Javascript,Jquery,Regex,Expression,我试图从URL中提取?ref值,并希望用其他值替换它 例如,假设我的URL是这样的,也可以是这样的 从上面的url中,我想找到?ref值,并想用另一个字符串替换它,比如“testing”。任何帮助,也希望学习高级正则表达式任何帮助 提前谢谢 为您发布的示例提供解决方案 str = str.replace(/\b(ref=)[^&?]*/i, '$1testing'); 正则表达式: \b the boundary between a word char (\w)
提前谢谢 为您发布的示例提供解决方案
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
修饰符用于不区分大小写的匹配
请参见确保url中没有两个“?”。我想你是说 您可以使用下面的功能 这里url是您的url,名称是键,在您的情况下它是“ref”,新的_值是新值,即替换“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);
}
试试这个:
var name = 'ref',
value = 'testing',
url;
url = location.href.replace(
new RegExp('(\\?|&)(' + name + '=)[^&]*'),
'$1$2' + value
);
newregexp('(\\?\;&)('+name+'=)[^&]*')
给出了/(\?\;&)(ref=)[^&]*/
,这意味着:
"?" or "&" then "ref=" then "everything but '&' zero or more times".
最后,$1
保存(\?|&)
的结果,而$2
保存(ref=)
的结果
链接如下:,。为什么url中有多个“?”?这可能只是一个例子。假设只有一个?那么这个表达是什么呢。