mynhylisti
mynhylisti

Reputation: 67

Highlight with color all words which starts with uppercase letter using Javascript

I'm newbie in Javascript and jQuery. I have a text inside a paragraph. I want to highlight with yellowgreen color all words which starts with uppercase letter. Here is my source code. But it does not works properly.

    <!DOCTYPE html>
    <html>
    <head>
<style>
.mycls {background-color:yellowgreen}
</style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        var str = $(p).text();

                words = str.split(' ');

                for (var i = 0; i < words.length; i++) {
                    var w = words[i].split('');

                    if (w.charAt(0) === w.charAt(0).toUpperCase()) {
                        $(this).addClass("mycls");
                    }

                 //   words[i] = letters.join('');
                }
    });
    </script>
    </head>
    <body>

    <p>President of USA Barack Obama is ...</p>

    </body>
    </html>

Thank you to all!

Upvotes: 2

Views: 1077

Answers (2)

Dimava
Dimava

Reputation: 10919

$('p').each(function(){ // to each <p>
  r = /[A-Z]\w*/g; // big letter with word symbols, global search
  function f(x){
    return '<span class="y">'+x+'</span>' // rewrited
  }
  h = $(this).html(); //get
  h = h.replace(r,f); //replace
  $(this).html(h); //set
}) //done
.y {
  background-color: yellowgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>President of USA Barack Obama is ...</p>

Upvotes: 2

DinoMyte
DinoMyte

Reputation: 8868

Try this :

<p>President of USA Barack Obama is ...</p>
<style>
.highlighted
{
 background-color: yellow;
}
</style>
<script>
var split = $('p').text().split("");
var upperCase= new RegExp('[A-Z]');
$.each(split,function(i)
{
  if(split[i].match(upperCase))
  {
    $('p').html($('p').html().replace(split[i],'<span class=\"highlighted\">' + split[i] + '</span>')); 
  }
});
</script>

Example : https://jsfiddle.net/DinoMyte/zhu7j8o6/5/

Upvotes: 1

Related Questions