简体   繁体   English

使用Javascript用彩色突出显示所有以大写字母开头的单词

[英]Highlight with color all words which starts with uppercase letter using Javascript

I'm newbie in Javascript and jQuery. 我是Javascript和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! 谢谢你们!

 $('p').each(function(){ // to each <p> r = /[AZ]\\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> 

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/ 范例: https : //jsfiddle.net/DinoMyte/zhu7j8o6/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM