Home > Web Front-end > JS Tutorial > body text

Example code for JavaScript filter keywords

黄舟
Release: 2017-03-20 14:22:53
Original
1366 people have browsed it

This article mainly introduces the JavaScript method of filtering keywords. Has very good reference value. Let’s take a look at it with the editor below

Rendering:

Example code for JavaScript filter keywords

Without further ado, please look at the code :

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
  em { font-size: 16px; color: red; }
 </style>
</head>
<body>
 <p id="cont">习近平哈哈哈周永康嘿嘿嘿中共哟西啪啪啪</p>
 <script>
  //================================= 可用状态代码 =====================================
//  var arr = [&#39;习近平&#39;,&#39;周永康&#39;,&#39;中共&#39;, &#39;嘿嘿&#39;],
//   arrText = arr.join(&#39;|&#39;),
//   var params = document.querySelector(&#39;#cont&#39;);
//
//  // 替换关键字
//  params.innerHTML = params.innerHTML.replace(new RegExp(arrText, "ig"), "<em>$&</em>");
//  var arr = [];
//  console.log(arr);

//================================= 修改后的代码 =====================================
  /**
   * 过滤关键字
   * @param keyArr 需要过滤的关键字数组
   * @param ele 过滤的节点
   */
  function filterContent(keyArr, ele) {
   /**
    * 一个程序的标准准则
    * 1. 可用, 可以实现核心的需求
    * 2. 健壮, 兼容性处理, 边界处理, 异常处理, 用户输入校验
    * 3. 可靠, 任何时候都要有返回值
    * 4. 宽容, 对需求宽容, 对调用着宽容, 对维护者宽容
    * 5. 精益求精, 可靠的注释...
    */
   try {
    // 检测是否为 undefined 或者为一个数组,或者数组长度是否大于 1, 这里的返回 -1 只是为了有返回值, 也可以不写
    if (keyArr === &#39;undefined&#39; || !(keyArr instanceof Array) || keyArr.length < 1) return -1;
    // 将数组里面的元素以 | 进行合并方便进行正则比较, 如 张三|李四
    var arrTxt = keyArr.join(&#39;|&#39;),
     regObj = new RegExp(arrTxt, &#39;ig&#39;);
    // 替换关键字
    ele.innerHTML = ele.innerHTML.replace(regObj, "<em>$&</em>");
   } catch (e) {
    console.log(&#39;出错啦~&#39; + e);
   }

  }
  // 调用
  var arr = [&#39;习近平&#39;,&#39;周永康&#39;,&#39;中共&#39;];
  var params = document.querySelector(&#39;#cont&#39;);
  filterContent(arr, params);
 </script>
</body>
</html>
Copy after login

The above is the detailed content of Example code for JavaScript filter keywords. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template