JS Regex,如何仅替换捕获的组? [英] JS Regex, how to replace the captured groups only?

查看:142
本文介绍了JS Regex,如何仅替换捕获的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的问题很简单。
我正在寻找像这样的字符串:

Ok the question is quite simple. I'm looking for a string like this one :

name="some_text_0_some_text"

我在上面的字符串之前和之后都有HTML代码。

现在我想用以下内容替换0:!NEW_ID!

Now i would like to replace the 0 by something like : !NEW_ID!

所以我做了一个简单的正则表达式:

So i made a simple regex :

.*name="\w+(\d+)\w+".*

但我不知道如何专门替换捕获的块。

But i don't see how to replace exclusively the captured block.

有没有办法可以替换一个其他字符串捕获的结果如($ 1)?

Is there a way to replace a captured result like ($1) by some other string ?

结果将是:

name="some_text_!NEW_ID!_some_text"

感谢您的帮助:)

推荐答案

解决方案是为前后文本添加捕获:

A solution is to add captures for the preceding and following text:

str.replace(/(.*value="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")

这篇关于JS Regex,如何仅替换捕获的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆