用颜色突出显示所有单词以大写字母开始使用JavaScript开始



我是JavaScript和jQuery中的新手。我在段落中有一个文字。我想用黄色颜色突出显示所有以大写字母开头的单词。这是我的源代码。但它无法正常工作。

    <!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>

谢谢大家!

$('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>

尝试以下:

<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>

示例:https://jsfiddle.net/dinomyte/zhu7j8o6/5/

最新更新