我在
JavaScript中有一个字符串,我想在其中找到给定短语的所有匹配项并用标记包装它们.我无法在这里找到正确的正则表达式方法来替换不区分大小写的短语,并用它周围的附加文本替换它自己.例如:
输入字符串:
"I like to play with cats,as does Cathy,who is a member of ACATA,which is the American Cat And Tiger Association."
不区分大小写的短语:“cat”
输出字符串:
"I like to play with <em>cat</em>s,as does <em>Cat</em>hy,who is a member of A<em>CAT</em>A,which is the American <em>Cat</em> And Tiger Association."
所以,基本上,注入< em>< / em>任何比赛.我不能只做一个直接替换,因为我将丢失输入字符串中的原始情况.
解决方法
你可以使用:
"Foo bar cat".replace(/(cat)/ig,"<em>$1</em>");
哪个将返回:
"Foo bar <em>cat</em>"