Skip to content Skip to sidebar Skip to footer

Jquery Uppercase Word Locator

I need to locate words for more than 4 characters that are written between

in uppercase and add them a style (ex. italic). I know about the function isUpperCas

Solution 1:

var ps = [].slice.call(document.getElementsByTagName("p"))

ps.forEach(function (p) {
  p.textContent.split(" ").forEach(function (word) {
    if (word.length > 4 && word.toUpperCase() === word) {
      // 4character UPPERCASE word
    }
  })
})

Solution 2:

You could use a regex to replace any uppercase text longer than four characters in the innerHTML of every <p> element with that text surrounded by the markup you're trying to insert:

$('p').each(function(){
    var pattern = /([-A-Z0-9]{4,})/g;
    var before = '<span style="color: red;">';
    var after = '</span>';
    $(this).html($(this).html().replace(pattern, before+"$1"+after));
});

http://jsfiddle.net/eHPVg/

Solution 3:

Yeah, like Rob said, I don't think Raynos's answer will work cross-browser and it also won't let you modify the matches within the paragraph.

Here's a slightly modified version:

var i = 0, ps = document.getElementsByTagName("p");

for(len = ps.length; i<len; i++)
{
    var p = ps[i];
    p.innerHTML = p.innerHTML.replace(/\b([A-Z]{4,})\b/g, "<span style='font-style:italic'>$1</span>"; 
}

You can change the span code to be whatever style you want to add. Just make sure to leave the $1, which refers the original uppercase word.

Post a Comment for "Jquery Uppercase Word Locator"