Day06 - Fetch、filter、正则表达式实现快速古诗匹配

简介:

Day06 - Fetch、filter、正则表达式实现快速古诗匹配

作者:©liyuechun
简介:JavaScript30 是 Wes Bos 推出的一个 30 天挑战。项目免费提供了 30 个视频教程、30 个挑战的起始文档和 30 个挑战解决方案源代码。目的是帮助人们用纯 JavaScript 来写东西,不借助框架和库,也不使用编译器和引用。现在你看到的是这系列指南的第 6 篇。完整中文版指南及视频教程在 从零到壹全栈部落。

效果图

在输入框中搜索字或者某个词快速匹配含有这个字或者是词的诗句。

涉及特性

  • flex布局
  • nth-child奇偶匹配
  • linear-gradient颜色渐变
  • transform
  • Fetch
  • Array

    • filter()
    • map()
    • push()
    • join()
    • ...
  • JavaScript RegExp 对象

    • 字面量语法
    • 创建 RegExp 对象的语法
    • 修饰符i、g
    • match()
    • replace()

实现步骤

  • UI布局
  • 通过Fetch下载数据
  • 数据处理并保存
  • 事件监听
  • 数据匹配操作
  • 新数据替换展示

布局篇

  • HTML代码
  <form class="search-form">
    <input type="text" class="search" placeholder="诗人名字,关键字">
    <ul class="suggestions">
      <li>输入词句,找一首诗</li>
      <li>输入词句,找一首诗</li>
      <li>输入词句,找一首诗</li>
      <li>输入词句,找一首诗</li>
      <li>输入词句,找一首诗</li>
    </ul>
  </form>
  • CSS代码
html {
  box-sizing: border-box;
  margin: 0px;
  background-color: rgb(145, 182, 195);
  font-family: 'Kaiti', 'SimHei', 'Hiragino Sans GB ', 'helvetica neue';
  font-size: 20px;
  font-weight: 200;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  display: flex;
  justify-content: center;
}

.search-form {
  max-width: 700px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

input.search {
  padding: 20px;
  font-family: 'Kaiti', 'helvetica neue';
  margin: 0;
  border: 10px solid #f7f7f7;
  font-size: 40px;
  text-align: center;
  width: 120%;
  outline: 0;
  border-radius: 5px;
  position: relative;
  top: 10px;
  left: 10px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.19);
}

.suggestions {
  margin: 0;
  padding: 0;
  position: relative;
  top: 7px;
  width: 100%;
}

.suggestions li {
  background: white;
  list-style: none;
  border-bottom: 1px solid #D8D8D8;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.14);
  margin: 0;
  padding: 20px;
  display: flex;
  flex-direction: column;
  /*align-items: flex-start;*/
}

span.title {
  margin-right: 20px;
  text-align: right;
  color: #7c8e94;
  margin-top: 5px;
}

span.hl {
  color: green;
}



/*偶数匹配*/
.suggestions li:nth-child(even) {
  transform: perspective(100px) rotateX(3deg) translateY(2px) scale(1.001);
  background: linear-gradient(to bottom, #ffffff 0%, #efefef 100%);
}

/*奇数匹配*/
.suggestions li:nth-child(odd) {
  transform: perspective(100px) rotateX(-3deg) translateY(3px);
  background: linear-gradient(to top, #ffffff 0%, #efefef 100%);
}

通过Fetch下载数据解析并且保存

const endpoint = 'https://gist.githubusercontent.com/liyuechun/f00bb31fb8f46ee0a283a4d182f691b4/raw/3ea4b427917048cdc596b38b67b5ed664605b76d/TangPoetry.json';

const poetrys = [];
fetch(endpoint)
 .then(blob => {
   return blob.json();
 })
 .then(data => {
   poetrys.push(...data);
 });

具体数据请求过程见下图:

Fetch详细使用文档

blob.json()是将数据转换为json数据,data为then函数中转换完的数据,在这个案例中,data是一个数组。

poetrys.push(...data)这句代码中的push是往数组里面新增对象,而...data代表的是将这个data数组中的数据一一的存储到poetrys数组中。

事件监听

const search = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

search.addEventListener('change', displayMatches);
search.addEventListener('keyup', displayMatches);

获取search和suggestions'节点分别对change、keyup事件进行监听,当输入框中的内容发生变化或者键盘弹起时触发displayMatches函数更新数据。

数据匹配操作

  • RegExp使用基础

RegExp参考文档

  • 项目源码分析
function findMatches(wordToMatch, poetrys) {
 return poetrys.filter(poet => {
   // 正则找出匹配的诗句
   const regex = new RegExp(wordToMatch, 'gi');
   const author = poet.detail_author.join('');
   //            console.log(author);
   return poet.detail_text.match(regex) || poet.title.match(regex) || author.match(regex);
 });
}

function displayMatches() {
 const matches = findMatches(this.value, poetrys);
 const regex = new RegExp(this.value, 'gi');
 const html = matches.map(poet => {
   // 替换高亮的标签
   const text = poet.detail_text.replace(regex, `<span class="hl">${ this.value }</span>`);
   const title = poet.title.replace(regex, `<span class="hl">${ this.value }</span>`);
   const detail_author = poet.detail_author[0].replace(regex, `<span class="hl">${ this.value }</span>`);
   // 构造 HTML 值
   return `
 <li>
   <span class="poet">${ text }</span>
   <span class="title">${ title } - ${ detail_author }</span>
 </li>
`;
 }).join('');
 //        console.log(html);
 suggestions.innerHTML = html;
}
  • poetrys.filter会返回带搜索关键字的新数组。
  • const regex = new RegExp(this.value, 'gi'); 代表匹配规则。
  • g:执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
  • i:执行对大小写不敏感的匹配。
  • 上面的这种写法等价于:"/this.value/gi"。
  • matches.map会返回一个按照新的规则处理完以后的新的数组。
  • title.replace(regex, "新字符串");表示将title字符串中满足 regex 规则的字符串替换成新字符串。

源码下载

Github Source Code

春哥简介

简介: 资深讲师,全栈工程师;区块链、高可用架构技术爱好者。
个人博客:http://liyuechun.org
新浪微博:黎跃春-追时间的人
github:http://github.com/liyuechun

技术交流

  • 区块链技术交流QQ群:348924182
  • 「区块链部落」官方公众号

相关文章
|
C#
C#的Winform中OpenFileDialog对话框Filter属性设置包含特定字符,使用正则表达式
OpenFileDialog对话框的Filter属性说明:          首先观察Filter属性的组成部分:“Word文件|*.doc ”,前面的“Word文件”成为标签,是一个可读的字符串,可以自定定义,“|*.doc”是筛选器,表示筛选文件夹中后缀名为.doc的文件,“*”表示匹配Word文件名称的字符串。
2432 0
Python 内置正则表达式库re的使用
正则表达式是记录文本规则的代码,用于查找和处理符合特定规则的字符串。在Python中,常通过原生字符串`r&#39;string&#39;`表示。使用`re.compile()`创建正则对象,便于多次使用。匹配字符串有`match()`(从开头匹配)、`search()`(搜索首个匹配)和`findall()`(找所有匹配)。替换字符串用`sub()`,分割字符串则用`split()`。
|
数据库 Python
Python网络数据抓取(8):正则表达式
Python网络数据抓取(8):正则表达式
|
自然语言处理 JavaScript 前端开发
Python高级语法与正则表达式(二)
正则表达式描述了一种字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹配的子串做替换或者从某个串中取出符合某个条件的子串等。
|
安全 算法 Python
Python高级语法与正则表达式(一)
Python提供了 with 语句的写法,既简单又安全。 文件操作的时候使用with语句可以自动调用关闭文件操作,即使出现异常也会自动关闭文件操作。
Python使用正则表达式分割字符串
在Python中,你可以使用re模块的split()函数来根据正则表达式分割字符串。这个函数的工作原理类似于Python内置的str.split()方法,但它允许你使用正则表达式作为分隔符。
Python中re模块的正则表达式
【6月更文挑战第2天】了解Python的re模块,它是处理正则表达式的核心工具。正则表达式用于在文本中查找特定模式。本文讨论了re模块的用法和技巧,包括导入模块、匹配、分组、替换文本、编译正则表达式以及使用预定义字符类、量词、锚点等高级功能。通过实例展示了如何在Python中执行这些操作,帮助提升文本处理能力。掌握这些技巧将使你更有效地利用正则表达式解决字符串处理问题。
|
数据安全/隐私保护 Python
Python进阶---正则表达式
Python进阶---正则表达式
245 2
|
数据采集 Python
python中的正则表达式,Python实习面试经验汇总
python中的正则表达式,Python实习面试经验汇总