【问题标题】:Replace a word only if it's not preceded by a certain character(s)仅当单词前面没有特定字符时才替换它
【发布时间】:2011-07-11 08:41:05
【问题描述】:

我喜欢替换 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”和“xbody”。但我只想用替换字符串替换“body”。该怎么做?

更多解释:

使用替换:

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(前面没有空格)。还将xbody 替换为HELLO,但我只想替换body 而不是xbody

希望这更清楚。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

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

    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 Demo

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

    更新:根据@yankee 的评论,我更改了正则表达式:添加了|^ 以使其在testHtmlStrhitName1 开头或等于它时起作用。

    【讨论】:

    • 如果 testHtmlStr = hitName1; 这将不起作用检查字符串 ([^&lt;\/]|\A) 的开头
    • 我修改了 alert(testHtmlStr.replace(re5, '$1'+replaceStr));我得到以下结果“这是一个带有 html 标记的测试字符串,带有常规 HELLO 字符串和另一个 html 字符串,没有 flexHELLO 并且 /body 在 url 字符串中”
    【解决方案2】:

    好吧,我不明白你到底想做什么,但我认为你正试图从包含标签和其他 textNodes 的字符串中替换一些标签

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

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

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 1970-01-01
      • 2019-10-28
      • 2012-08-11
      • 1970-01-01
      • 2017-06-17
      • 2014-01-06
      • 2013-05-19
      • 2020-03-31
      相关资源
      最近更新 更多