Reputation: 2031
I want to change a block of output from this:
<div>Lorem ipsum dolor sit amet (consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt)</div>
to this:
<div>Lorem ipsum dolor sit amet <span class="italics">(consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt)</span></div>
JavaScript:
var div = $('div');
var matches = div.match(/\((.*?)\)/);
if (matches) {
matches.css('color', 'red');
}
Basically, use regex to wrap everything in (here) with an addClass. Any ideas?
I feel like this is close: http://jsfiddle.net/saltcod/DjHUt/
Upvotes: 0
Views: 330
Reputation: 194
This should do the job: http://jsfiddle.net/cqTq7/2/
Here is my code:
var div = $('div'),
divHTML = div.html();
var match = divHTML.match(/\((.*?)\)/);
divHTML = divHTML.replace(match[0], '<span class="italics">$&</span>');
div.html(divHTML);
Note that the match
function is a function in JavaScript, not jQuery. Here I also use the JavaScript replace
function.
Upvotes: 0
Reputation: 144689
You can use html
method:
$('div').html(function(i, h){
return h.replace(/\((.*?)\)/, '<span class="italics">$&</span>');
})
Upvotes: 1
Reputation: 14187
Try this:
div = $('div');
div.html(div.text().replace(/\([^)]+\)/g, '<span class="italics">$&</span>'));
Live Demo:
http://jsfiddle.net/oscarj24/weJWL/
Upvotes: 0