Javascript regexp:在反向引用模式中使用变量

Javascript regexp: Using variables in backreference pattern?

本文关键字:模式 变量 引用 regexp Javascript      更新时间:2023-09-26

我有一个模式来查找匹配的查询字符串:

'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test')

我希望能够做的是使用变量值作为参数来匹配,如:

'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test')

[edit]下面是如何使用代码的上下文:

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;
        }

但是它不像预期的那样工作-有人能帮忙吗?

如果选择从字符串构造正则表达式,则需要去掉分隔符(但是如果正则表达式包含反斜杠,则需要将反斜杠加两)。试着

myregex = new RegExp('(' + key + '=)([^&]*)')
'url.com/foo/bar?this=that&thing=another'.replace(myregex, '$1test')

您是否知道这也将匹配url.com/foo/bar?something=another中的thing=another ?为了避免这种情况,可以添加一个词边界锚:

myregex = new RegExp('(''b' + key + '=)([^&]*)')