首页 > 解决方案 > 如何用找到的不区分大小写的正则表达式替换匹配项,但扩展结果

问题描述

简单地说,我有字符串:Hello and good morning world.并且我有一个搜索字符串:Good

我想匹配搜索字符串不区分大小写的所有内容,但我需要将结果扩展为:

Hello and <mark>good</mark> morning world.

我还在做一些研究,但它看起来比我想象的要复杂。我希望你能帮忙。到目前为止,我找不到任何类型的线程。希望你能给我指出一个甚至解决这个问题。非常感谢。

标签: javascript

解决方案


replace通过在正则表达式中指定忽略和全局大小写,您可以使用字符串函数获得预期结果:

var string = 'Hello and good morning world.';

var result = string.replace(/(Good)/ig, '<mark>$1</mark>');

console.log(result);


推荐阅读