0

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/

1

3 Answers 3

1

You can use html method:

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

http://jsfiddle.net/WmCLz/

Sign up to request clarification or add additional context in comments.

3 Comments

Or just use $& and remove the capturing group... You also need g flag just in case
@nhahtdh Yes, if it should be global, g flag is needed. I just used the OP's regex.
I don't get why you get -1... I have upvoted your answer, since it is a reasonable answer.
0

Try this:

div = $('div');
div.html(div.text().replace(/\([^)]+\)/g, '<span class="italics">$&</span>'));

Live Demo:

http://jsfiddle.net/oscarj24/weJWL/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.