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

发布于 2024-10-30 21:00:01 字数 741 浏览 0 评论 0原文

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

'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽你眉间 2024-11-06 21:00:01

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

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 + '=)([^&]*)')

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

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

Are you aware that this would also match thing=another in url.com/foo/bar?something=another? To avoid this, add a word boundary anchor:

myregex = new RegExp('(\\b' + key + '=)([^&]*)')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文