gpt4 book ai didi

javascript - js中基于正则表达式的替换

转载 作者:行者123 更新时间:2023-11-30 13:26:40 25 4
gpt4 key购买 nike

实际上我想替换一个字符串,除非它出现在圆括号中。

例如:

JAVA is a nice language. (JAVA) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.

现在如果我用 C 替换 JAVA:

然后期望的输出是:

C is a nice language. (JAVA) has lots of features. C is portable. (JAVA) even comes in 64 bit. 

甚至java也可以作为子字符串出现

 XJAVAX is a nice language. (XJAVAX) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.

现在,如果我用 C 替换 JAVA:

然后预期的输出:

XCX is a nice language. (XJAVAX) has lots of features. C is portable. (JAVA) even comes in 64 bit.

最佳答案

由于 JavaScript 没有后视,最简单的方法可能是交替:

str = str.replace(/\(JAVA\)|JAVA/g, function(m) {
return m === "(JAVA)" ? m : "C";
// Or
// return m.length === 6 ? m : "C";
});

除此之外,您开始尝试 simulate look-behind ,这在某些方面是可能的,但很麻烦。

关于javascript - js中基于正则表达式的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com