仅当单词'前没有特定字符时替换它

Replace a word only if it's not preceded by a certain character(s)

本文关键字:字符 替换 单词      更新时间:2023-09-26

我喜欢替换JavaScript中字符串的所有出现,其中字符串不以</开始。我能够匹配单词,但我只想替换单词,而不是前面的字符。

var hitName1 = "body";
var testHtmlStr = "This is a test string with <body> html tag and with regular body string and another <body> html string and with no flexbody and with /body as in a url string";
var re5 = new RegExp('[^<'/]' + hitName1 , 'gi');
console.log(re5);
var testResult5 = testHtmlStr.match(re5);
console.log(testResult5);

我得到结果[" body", "xbody"]

如果我使用replace()而不是match(),我将用替换字符串替换"body"answers"xbody"。但我想只替换"体"与替换字符串。怎么做呢?

更多解释:

var testResult5 = testHtmlStr.replace(re5, "HELLO");
console.log(testResult5);

替换后的结果字符串:

"This is a test string with <body> html tag and with regularHELLO string and another <body> html string and with no fleHELLO and with /body as in a url string"

替换函数将body替换为HELLO,但我想替换body(与nospace infront)。另外,xbody替换为HELLO,但我只想替换body而不是xbody

一种方法是在前面的字符周围定义一个捕获组:

var hitName1='body';
var testHtmlStr = "This is a test string with <body> html tag and with regular body string and another <body> html string and with no flexbody and with /body as in a url string";
var re5 = new RegExp('([^<'/]|^)' + hitName1, 'gi');
alert(testHtmlStr.replace(re5, '$1'));

jsFiddle演示

例如,如果你想用fos替换字符串,你可以写$1fos

UPDATE:跟随@yankee的评论,我已经改变了regex:添加了|^,使其在testHtmlStrhitName1开始或等于它时工作

嗯,我无法理解你到底想做什么,但我认为你正试图从包含标签和其他textNodes的字符串中替换一些标签

然而,我认为如果你使用"for"循环来验证哪些标签应该被替换,哪些标签不应该被替换,你将能够做你需要的。

for(result in testResult5)
{
    if(result!="body") {// do what you want}
}