javascript - 用正则表达式替换第 n 个匹配项

标签 javascript regex string

我正在尝试找到一种方法来替换更多匹配项中的第 n 个匹配项。

string = "one two three one one"

如何定位第二次出现的“one”?

有没有可能做这样的事情?

string.replace(/\bone\b/gi{2}, "(one)")

得到这样的东西

"one two three (one) one"

我做了一个 jsfiddle,它可以工作,但感觉不对。一堆代码和简单的事情令人困惑。

https://jsfiddle.net/Rickii/7u7pLqfd/

最佳答案

更新:

要使其动态使用:

((?:.*?one.*?){1}.*?)one

其中值 1 表示 (n-1);在你的情况下是 n=2

并替换为:

$1\(one\)

Regex101 Demo

const regex = /((?:.*?one.*?){1}.*?)one/m;
const str = `one two three one one asdfasdf one asdfasdf sdf one`;
const subst = `$1\(one\)`;
const result = str.replace(regex, subst);
console.log( result);

关于javascript - 用正则表达式替换第 n 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943096/

相关文章:

javascript - 如何显示数据库中的分割日期

javascript - 如何在 ASP.NET 页面中实现倒计时器?

javascript - 如何使用 jQuery 从外部 URL 获取元标记

java - 正则表达式文件名模式匹配

javascript - HTML 节点图生成器?

regex - 使用 grep 将 BBEdit 中的空格转换为制表符

javascript - 用于提取js函数onclick ="unSelAll(' FBtest11_ 6',this.value,this.id)"的正则表达式

c++ - 我无法使用功能将字符串内的字符加倍

c# - 性能 - str_01 == str_02 vs (object)str_01 == (object)str_02

Sql Only 字符串搜索