我想给文章里面的垃圾邮件上色

时间:2019-04-25 14:35:34

标签: javascript jquery

我想写一个程序。该程序将在文章中查找垃圾邮件并为其着色。我找到了垃圾邮件,但我无法给它上色。我写了一个错误的代码。我知道。

我的代码是这样的:

  $("button").click(function(){
    var source = $("p").text();
    function findSpam(txt){
      if(!txt) return `no string...`;
      let spamWords = ["codeblogger","truecodes","metus","xxx"];
      for(let i = 0; i < spamWords.length; i++){
        if(txt.toLowerCase().includes(spamWords[i])){
          source.indexOf(spamWords[i]).style.color = "blue"; // not work :)
          return 'This article has spam.';
        }else{
          return `This article has not spam.`;
        }
      } 
    };
    alert(findSpam(source));
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
    <div id="box">
      <h1 class="text-center mt-5 pb-3">Lorem Ipsum</h1>
      <p id="text" >
       ........... I shorten the article.
        
        Integer euismod consequat ex sed feugiat. Morbi sed sem in ipsum scelerisque 
        elementum. Phasellus et tristique odio. Ut lacus dolor, tincidunt eget magna 
        sed, dignissim lobortis risus. Vivamus volutpat vel dui ut elementum. Maecenas 
        ultricies, erat sed egestas finibus, tellus nibh hendrerit sem, id imperdiet 
        est lorem sit amet lacus. Quisque scelerisque nisl id sapien porttitor, tristique 
        pharetra mi iaculis. Vestibulum ac arcu lobortis, posuere dolor non, condimentum 
        est. Nam non efficitur nunc, fringilla sollicitudin ante. Curabitur quis metus 
        tellus truecodes codeblogger codeblogger xxx.
      </p>
      <button type="button" class="btn btn-danger btn-lg btn-block">FIND SPAM</button>
    </div>
  </div>


此外:

该代码发现垃圾邮件。没问题。但我也想找到垃圾邮件的数量。我怎么做。我已经尝试过这种方式:

  $("button").click(function(){
    var source = $("p").text();
    function findSpam(txt){
      let totalSpam = 0;
      if(!txt) return `no string...`;
      let spamWords = ["codeblogger","truecodes","metus","xxx"];
      for(let i = 0; i < spamWords.length; i++){
        if(txt.toLowerCase().includes(spamWords[i])){
          totalSpam ++;
        }
      }
      return totalSpam; 
    };
    alert(`Total spam: ${findSpam(source)}`); 
    // output: 4. But there are a total of 8 in the article.
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
    <div id="box">
      <h1 class="text-center mt-5 pb-3">Lorem Ipsum</h1>
      <p id="text" >
        .......
        Integer euismod consequat ex sed feugiat. Morbi sed sem in ipsum scelerisque 
        elementum. Phasellus et tristique odio. Ut lacus dolor, tincidunt eget magna 
        sed, dignissim lobortis risus. Vivamus volutpat vel dui ut elementum. Maecenas 
        ultricies, erat sed egestas finibus, tellus nibh hendrerit sem, id imperdiet 
        est lorem sit amet lacus. Quisque scelerisque nisl id sapien porttitor, tristique 
        pharetra mi iaculis. Vestibulum ac arcu lobortis, posuere dolor non, condimentum 
        est. Nam non efficitur nunc, fringilla sollicitudin ante. Curabitur quis metus 
        tellus truecodes codeblogger codeblogger xxx xxx xxx.
      </p>
      <button type="button" class="btn btn-danger btn-lg btn-block">FIND SPAM</button>
    </div>
  </div>

2 个答案:

答案 0 :(得分:1)

这是计算7个实例的方法:

let spamWords = ["codeblogger", "truecodes", "metus", "xxx"];
function findSpam(txt) {
  let totalSpam = 0;
  if (!txt) return `no string...`;
  spamWords.forEach(word => {
    var re = new RegExp(word, "gi");
    totalSpam += txt.match(re).length;
  })
  return totalSpam;
};

$("button").click(function() {
  var source = $("p").text();
  console.log(`Total spam: ${findSpam(source)}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div id="box">
    <h1 class="text-center mt-5 pb-3">Lorem Ipsum</h1>
    <p id="text">
      ....... Integer euismod consequat ex sed feugiat. Morbi sed sem in ipsum scelerisque elementum. Phasellus et tristique odio. Ut lacus dolor, tincidunt eget magna sed, dignissim lobortis risus. Vivamus volutpat vel dui ut elementum. Maecenas ultricies,
      erat sed egestas finibus, tellus nibh hendrerit sem, id imperdiet est lorem sit amet lacus. Quisque scelerisque nisl id sapien porttitor, tristique pharetra mi iaculis. Vestibulum ac arcu lobortis, posuere dolor non, condimentum est. Nam non efficitur
      nunc, fringilla sollicitudin ante. Curabitur quis metus tellus truecodes codeblogger codeblogger XXX xxx xxx.
    </p>
    <button type="button" class="btn btn-danger btn-lg btn-block">FIND SPAM</button>
  </div>
</div>

我没有时间修复要替换的循环:

let spamWords = ["codeblogger", "truecodes", "metus", "xxx"];

function findSpam(txt) {
  let totalSpam = 0;
  if (!txt) return `no string...`;
  spamWords.forEach(word => {
    var re = new RegExp(word, "gi");
    totalSpam += txt.toLowerCase().match(re).length;
  })
  return totalSpam;
};

function replaceSpam() {
  let txt = $("p").text().toLowerCase()
  spamWords.forEach(word => {
    let parts = txt.split(/\s/);
    if (parts.indexOf(word) != -1) {
      var re = new RegExp(word, "gi");
      txt.match(re).filter((v, i, a) => a.indexOf(v) === i).forEach(uWord => {
        var replaced = $("p").text().replace(
          new RegExp(uWord, "g"),
          function(w) {
            return `<span class="spam">${w}</span>`
          }
        );
        console.log(replaced)
        $("p").html(replaced)
      })
    }
    txt = $("p").text().toLowerCase()
  })
}
$("button").click(function() {
  var source = $("p").text();
  console.log(`Total spam: ${findSpam(source)}`);
  replaceSpam(source)
});
.spam {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div id="box">
    <h1 class="text-center mt-5 pb-3">Lorem Ipsum</h1>
    <p id="text">
      ....... Integer euismod consequat ex sed feugiat. Morbi sed sem in ipsum scelerisque elementum. Phasellus et tristique odio. Ut lacus dolor, tincidunt eget magna sed, dignissim lobortis risus. Vivamus volutpat vel dui ut elementum. Maecenas ultricies,
      erat sed egestas finibus, tellus nibh hendrerit sem, id imperdiet est lorem sit amet lacus. Quisque scelerisque nisl id sapien porttitor, tristique pharetra mi iaculis. Vestibulum ac arcu lobortis, posuere dolor non, condimentum est. Nam non efficitur
      nunc, fringilla sollicitudin ante. Curabitur quis metus tellus truecodes codeBlogger codeblogger XXX xxx xxx.
    </p>
    <button type="button" class="btn btn-danger btn-lg btn-block">FIND SPAM</button>
  </div>
</div>

答案 1 :(得分:1)

这是一个解决方案:

$("button").click(function() {
  var source = $("p").text();
  var newSource = source;
  var result = 'This article has not spam.';

  if (!source) alert("no string...");
  let spamWords = ["codeblogger", "truecodes", "metus", "xxx"];
  for (let i = 0; i < spamWords.length; i++) {
    if (source.toLowerCase().includes(spamWords[i])) {
      newSource = newSource.replace(spamWords[i], '<span style="color:red;font-weight:bold;text-decoration:underline;">' + spamWords[i] + '</span>');
      result = 'This article has spam.';
    }
  }

  $("#text").html(newSource);
  console.log(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<div class="container">
  <div id="box">
    <h1 class="text-center mt-5 pb-3">Lorem Ipsum</h1>
    <p id="text">
      ........... I shorten the article. Integer euismod consequat ex sed feugiat. Morbi sed sem in ipsum scelerisque elementum. Phasellus et tristique odio. Ut lacus dolor, tincidunt eget magna sed, dignissim lobortis risus. Vivamus volutpat vel dui ut elementum.
      Maecenas ultricies, erat sed egestas finibus, tellus nibh hendrerit sem, id imperdiet est lorem sit amet lacus. Quisque scelerisque nisl id sapien porttitor, tristique pharetra mi iaculis. Vestibulum ac arcu lobortis, posuere dolor non, condimentum
      est. Nam non efficitur nunc, fringilla sollicitudin ante. Curabitur quis metus tellus truecodes codeblogger codeblogger xxx.
    </p>
    <button type="button" class="btn btn-danger btn-lg btn-block">FIND SPAM</button>
  </div>
</div>



</script>