Javascript regexp:在反向引用模式中使用变量?
我有一个在查询字符串中查找匹配项的模式:
'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test')
我想要做的是使用变量值作为参数来匹配,例如:
'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test')
[编辑]以下是如何使用代码的上下文:
GetSrcParam: function(key, value) {
var newSrc = $(this._image).attr('src'),
pattern = '(' + key + '=)([^&]*)';
if (newSrc.match(pattern) == null)
newSrc += '&' + key + '=' + value;
else
newSrc = newSrc.replace(newSrc, '$1' + value);
return newSrc;
}
但它是没有按预期工作 - 有人可以帮忙吗?
I've got a pattern to find matches in a querystring:
'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test')
What I'd like to be able to do is use variable values as the param to match like:
'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test')
[edit] Here's the context in how the code is being used:
GetSrcParam: function(key, value) {
var newSrc = $(this._image).attr('src'),
pattern = '(' + key + '=)([^&]*)';
if (newSrc.match(pattern) == null)
newSrc += '&' + key + '=' + value;
else
newSrc = newSrc.replace(newSrc, '$1' + value);
return newSrc;
}
But it's not working as intended - can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您选择从字符串构造正则表达式,则需要删除分隔符(但如果您的正则表达式要包含任何反斜杠,则需要将反斜杠加倍)。尝试
您知道这也会匹配
url.com/foo/bar?something=another
中的thing=another
吗?为了避免这种情况,请添加单词边界锚:If you choose to construct a regex from a string, you need to drop the delimiters (but then you need to double any backslashes, if your regex were to contain any). Try
Are you aware that this would also match
thing=another
inurl.com/foo/bar?something=another
? To avoid this, add a word boundary anchor: