views:

269

answers:

2

Hello

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

Simple problem but too hard for my mind :-D Any help?

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

Martti Laine

+1  A: 

Here's a useful jQuery plugin.

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

Pointy
There's no need to use tinyurl on StackOverflow, that's what Markdown is for.
Tobias Cohen
Thanks, easy to use!
Martti Laine
A: 

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

$('#container').html($('#container').html().replace(/(dog)/g,'<span class="highlight">$1</span>'));
Chris Bartow
.val() should only work on form elements. You need .text() here - if I'm not wrong atm.
asrijaal
you are not wrong - this answer won't actually work given the original question, which is about words in running text, not in form elements. Even then, putting span tags inside form element values would not work anyway.
Pointy
Actually, it's html(). Code fixed and tested.
Chris Bartow