daniel__
daniel__

Reputation: 11845

add class to last word

My question is why the phrase is red. Should be only the word after >. The regular expression is correct (here)

$(".some").html(function (i, text) {
    return text.replace(/([^>]*)$/, function (match) {
        return '<span class="red">' + match + '</span>';
    });
});

.red {
    color:#ff0000
}

<div class="some">RAW MATERIALS & CHEMICALS>Earth & Stone</div>

http://jsfiddle.net/Z4cMN/1/

Upvotes: 3

Views: 846

Answers (3)

lonesomeday
lonesomeday

Reputation: 238015

There is another way to do this that is a bit nicer than the regex way. It is using the power of the DOM: it is therefore the way that the browser itself understand the webpage.

var textnode = $(".some").contents().last().get(0), // get the last node in .some
    last = textnode.splitText(textnode.data.lastIndexOf('>') + 1); // split it after the last >

$(last).wrap('<span class="red"/>'); // wrap the newly-created node in a span

http://jsfiddle.net/Z4cMN/11/

Note that this allows us to use the text data in a more intuitive way, rather than worrying about HTML encoding.

Upvotes: 2

Trevor Dixon
Trevor Dixon

Reputation: 24392

text has special characters html encoded, so you should be looking for &gt;.

http://jsfiddle.net/trevordixon/Z4cMN/10/

$(".some").html(function (i, text) {
    return text.replace(/&gt;(.*)$/, function (match, title) {
        return '&gt;<span class="red">' + title + '</span>';
    });
});

Upvotes: 4

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

Seems like the HTML & and > are escaped. Try unescaping the characters before passing it to the regEx.

$(".some").html(function (i, text) {
    return htmlDecode(text).replace(/([^>]*)$/, function (match) {
        return '<span class="red">' + match + '</span>';
    });

    function htmlDecode(input) {
        var e = document.createElement('div');
        e.innerHTML = input;
        return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
    }
});

DEMO: http://jsfiddle.net/fptbd/

Upvotes: 3

Related Questions