【问题标题】:How to find and replace text using regex?如何使用正则表达式查找和替换文本?
【发布时间】:2020-07-04 14:53:17
【问题描述】:

我有以下文本作为输入。

This is specified input. This is Specified input.

我想要下面的输出。

This is <span>specified</span> input. This is <span>Specified</span> input.

如果我这样做str.replace(\specified\gi, '<span>specified</span>'),它将像这样替换

This is <span>specified</span> input. This is <span>specified</span> input.

如何用匹配的元素替换这个字符串

【问题讨论】:

    标签: javascript html regex dom


    【解决方案1】:

    替换为<span>$&<span> 以插入匹配的文本:

    const str = 'This is specified input. This is Specified input.';
    const result = str.replace(/specified/gi, '<span>$&<span>');
    console.log(result);

    【讨论】:

      【解决方案2】:

      使用$&amp; 检索匹配的字符串。

      您的正则表达式周围的斜线也有错误。

      var str = "This is specified input. This is Specified input.";
      console.log(str.replace(/specified/gi, '<span>$&</span>'));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多