Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

JavaScript regex - How to wrap matches with tag?

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:

Input string:

"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"

Output string:

"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."

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use:

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

Which will return:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...