tags:

views:

47

answers:

1

I've got a bunch of h4 tags that I want to wrap in a <span class="red"> </span>

Some of the text is like this: $12 and some has a space like $ 5

How can I wrap all instances of $ and the numbers that follow with jQuery?

Let me clarify. I want to have this <h4> this item is <span class="red">$42</span> and on sale</h4>

+1  A: 

I would do it with a regular expression. Something like:


var tempString = $("h4").html().replace(/^(.*)(\$\s*\d+)(.*)$/, '$1<span>$2</span>$3');
$("h4").html(tempString);

The regular expression might need some modification depending on your situation. In the second part of the replace, simply put the '$2' inside span tags with the class you want to add.

Roxtonic
I don't know `'how to regular expression'` but I made you a [fiddle](http://jsfiddle.net/rzZTG/). Really wish I know how. +1
Reigel
Thanks, Reigel, for the fiddle that proved the regular expression I didn't actually test works!
Roxtonic
@Roxtonic, the regex works, but the jQuery in your example will replace all `h4` elements with the same html. See [here](http://jsfiddle.net/gmnHa/). You could go with either @Reigel's example or use jQuery's `each` function.
Bryan
I assume you mean something like `$("h4").each(function() { ... })`
Sean Hogan
Yeah, I know I guess I assumed there would be only one h4 in my example. Use each()
Roxtonic