Wrap some specified words with span in jQuery?

2019-01-15 10:09发布

I'd like to know the most convenient way to wrap some specified words with span-tags.

Example: I have a word, which is dog. Here's the original text:

I have a dog, do you have a dog?

And output should be like this:

I have a <span class="highlight">dog</span>, do you have a <span class="highlight">dog</span>?

Any help?

EDIT: Note, that it should also wrap words, even if they are not invidual (Peter-dog). Hope you got it.

2条回答
闹够了就滚
2楼-- · 2019-01-15 10:30

You can use the JavaScript replace function. Here is a basic example:

$('#container').html($('#container').html().replace(/(dog)/g,'<span class="highlight">$1</span>'));
查看更多
smile是对你的礼貌
3楼-- · 2019-01-15 10:32

Here's a useful jQuery plugin.

It's really easy to use and it works great.

edit — this is a very old answer of mine. I regret having simply linked the Lettering.js library without including its name. The library is useful, though I'm not sure here 7 years later whether Mr. Rupert continues to actively maintain it.

What Lettering does is go through the text nodes in a selected region of the DOM and wrap the individual letters and/or words (configurable) in <span> tags that can then be styled. It's simple but effective. Even if you don't want to use it, the code is not very extensive and it's instructional.

查看更多
登录 后发表回答