Reputation: 11845
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>
Upvotes: 3
Views: 846
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
Note that this allows us to use the text data in a more intuitive way, rather than worrying about HTML encoding.
Upvotes: 2
Reputation: 24392
text
has special characters html encoded, so you should be looking for >
.
http://jsfiddle.net/trevordixon/Z4cMN/10/
$(".some").html(function (i, text) {
return text.replace(/>(.*)$/, function (match, title) {
return '><span class="red">' + title + '</span>';
});
});
Upvotes: 4
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