代码之家  ›  专栏  ›  技术社区  ›  pirmax

在文本中替换数组中的哈希标记的正则表达式

  •  0
  • pirmax  · 技术社区  · 6 年前

    我尝试用标签替换文本,并从数组中删除使用的单词。

    我的阵列:

    ['Test', 'NodeJS', 'regex']
    

    这里,用NodeJS测试regex!

    变成:

    在这里,用NodeJS测试Regex!

    你能指导我如何使用NodeJS和regex吗?

    0 回复  |  直到 6 年前
        1
  •  0
  •   trincot Jakube    6 年前

    你可以用它 reduce , new RegExp replace 使用回调函数(用于将单词标记为已用):

    var tags = ['Test', 'NodeJS', 'notfound', 'regex']
    var s = "Here, test with NodeJS to try regex !";
    
    s = tags.reduce((acc, tag, i) => 
        acc.replace(new RegExp("\\b" + tag + "\\b", "gi"), () => {
            tags[i] = null;
            return "#" + tag;
        }), s);
    tags = tags.filter(Boolean);
    console.log(s);
    console.log(tags);

    如果数组包含需要转义的具有特殊字符的字符串,请首先对其进行转换,如中所述 this Q&A .

    如果您只想替换 第一 出现特定标记,然后删除“g”修饰符。