Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript正则表达式:在反向引用模式中使用变量?_Javascript_Regex_Backreference - Fatal编程技术网

Javascript正则表达式:在反向引用模式中使用变量?

Javascript正则表达式:在反向引用模式中使用变量?,javascript,regex,backreference,Javascript,Regex,Backreference,我有一个在查询字符串中查找匹配项的模式: 'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test') 我希望能够使用变量值作为参数进行匹配,如: 'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test') [编辑]以下是代码使用的上下文: GetSrc

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

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

但是它没有按预期工作-有人能帮忙吗?

如果选择从字符串构造正则表达式,则需要删除分隔符(但如果正则表达式包含任何反斜杠,则需要将任何反斜杠加倍)。试一试

您是否知道这也会匹配
url.com/foo/bar中的
thing=other
?something=other
?要避免这种情况,请添加单词边界锚定:

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

欢迎来到SO。请使用代码格式TNG(您只需按一个按钮即可)另外,请提供一些JS代码,而不仅仅是模式本身。问题可能在于你如何准备你的模式。抱歉,没有注意到它-已经更新了js正在(或想要)使用的上下文。
myregex = new RegExp('(\\b' + key + '=)([^&]*)')