saltcod
saltcod

Reputation: 2031

jQuery addClass from regex match

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

Answers (3)

BahamutWC
BahamutWC

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

Ram
Ram

Reputation: 144689

You can use html method:

$('div').html(function(i, h){
   return h.replace(/\((.*?)\)/, '<span class="italics">$&</span>');
})

http://jsfiddle.net/WmCLz/

Upvotes: 1

Oscar Jara
Oscar Jara

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

Related Questions