JavaScript正则表达式-如何用标记包装匹配项? [英] JavaScript regex - How to wrap matches with tag?

查看:37
本文介绍了JavaScript正则表达式-如何用标记包装匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有一个字符串,我想在其中找到给定短语的所有匹配项,并用标记将它们包装起来.我在这里找不到正确的regex方法来替换不区分大小写的短语,并用其周围的其他文本替换为它自己.例如:

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:

输入字符串:

"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."

不区分大小写的词组:猫"

Case insensitive phrase: "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>.我不能只做一个简单的替换,因为我会丢失输入字符串中的原始大小写.

So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.

推荐答案

您可以使用:

"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");

哪个会返回:

"Foo bar <em>cat</em>"

这篇关于JavaScript正则表达式-如何用标记包装匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆