Skip to content Skip to sidebar Skip to footer

Jquery - Change Color Of String In A Text, Ignoring
's Between

I need to change the color of a specific sub-string in a text. The text looks like this: SOME TE XT IS HER E. I tired the .replace() function from jquery, the

Solution 1:

No jQuery required. Although I did not test this at all so it might need tweaking.

var customReplace = function(str, subStr, color) {
    var words = str.split(' ');
    for (var i = words.length - 1; i >= 0; i--) {
        var word = words[i].replace(/<br>/g, '');
        if (word === subStr) {
            words[i] = '<span class="color-' + color + '">' + words[i] + '</span>';
        }
    }

    return words.join('');
}

Solution 2:

I think a good Idea could be something like following:

  1. fine all text nodes and wrap them inside a span§
  2. re-insert all tags

varALL_TAGS_REGEX = /(.+)(<{1}\/{0,1}.+>{1})/g;

document.addEventListener("DOMContentLoaded", function() {
  document.body.innerHTML = document
    .body
    .innerHTML
    .replace(ALL_TAGS_REGEX, '<span class="highlight">$1</span>$2')
  ;
});
.highlight { background: cyan; }
I am a string,<br><div> something else but no text node</div>
Other text nodes at libitum

Solution 3:

< br > tag is break in line, color won't be applicable on < br > text, this would not accounted as normal text while final html render

Post a Comment for "Jquery - Change Color Of String In A Text, Ignoring
's Between"