正在加载...

正则表达式

拿去对文本跑的模式,就是正则表达式。/tea/ 只问 tea 在不在。replace 返回一条新字符串,把那个位置写成 mint。这一页的 note 是 Order: tea,看得见的那一行是 true / Order: mint。

地图那页在存放,这一页在查找

地图那一页停在 lida / mint / 2,那是在存放。这一页不存放客人。它在一条字符串里查找。查找失败就得到 false 或 null,不会抛出错误。

模式已经坐在里面,或者根本没有

加上 i 标志就不管大小写,所以 /tea/i 能对上 Tea。模式已经坐在 mint tea 里面,/tea/.test("mint tea") 就是 true。lemon 里没有它,/tea/.test("lemon") 就是 false。

文本里有没有 tea

javascript
console.log(/tea/.test("mint tea"));
console.log(/tea/.test("lemon"));

日志先是 true,接着是 false。点号匹配任意一个字符,但不包括换行,所以 /t.a/ 也能匹配 tea。真正的句点要写成反斜杠再加一个点:\。

要求整条字符串

^ 表示开头,$ 表示结尾。/^tea$/ 接受 tea,拒绝 mint tea。没有这两处标记时,/tea/ 在更长的笔记里照样成功。

整条订单

javascript
console.log(/^tea$/.test("tea"));
console.log(/^tea$/.test("mint tea"));

日志是 true,然后是 false。mint tea 里有这些字母,但它并不只是 tea。

每一份,然后一条新字符串

带上 g 标志,match 会把每一份都交回来。replace 带上 g 会换掉每一份,并返回一条新字符串。在你把结果赋回去之前,note 保持不动。

两处都找到,再替换

javascript
const note = "tea and tea";
console.log(note.match(/tea/g));
console.log(note.replace(/tea/g, "mint"));
console.log(note);

match 的日志是含有两个 tea 字符串的数组。replace 的日志是 mint and mint。第三条日志仍是 tea and tea,因为 replace 没有改 note。不加 g 时,只有第一处 tea 会变。什么都没匹配到时,match 返回 null,不是空数组。

按答案的形状选方法

要哪种形状的答案,就选哪种方法。

📊 每个方法返回什么

方法 答案的形状 在这条笔记上
/tea/.test(note) true 或 false 对 Order: tea 是 true
note.match(/tea/) 一次匹配的数组,或 null 单词 tea 以及它所在的位置
note.match(/tea/g) 每一份,或 null tea and tea 里有两份
note.replace(/tea/, "mint") 一条新字符串 Order: mint

test 只回答是或否。match 把片段交给你。replace 把改写后的文本交给你。想留下它,就赋值。

页面把两个结果都写上

这一页测试 Order: tea,换掉饮料,再把两个结果都写出来。

页面那一行:test 与 replace

html
<!DOCTYPE html>
<html>
<body>
<p id="line">…</p>
<script>
const note = "Order: tea";
const found = /tea/.test(note);
const next = note.replace(/tea/, "mint");
document.querySelector("#line").textContent = found + " / " + next;
</script>
</body>
</html>

这一行读作 true / Order: mint。note 本身仍是 Order: tea。lida / mint / 2 属于地图那一页。

五个短练习

  1. 用 /tea/ 测试 mint tea。结果是 true。
  2. 用 /tea/ 测试 lemon。结果是 false。
  3. 用 /^tea$/ 测试 mint tea。结果是 false。
  4. 用 /tea/g 匹配 tea and tea。数组长度是 2。
  5. 读这一页。那一行是 true / Order: mint。

易错处,以及要记住的

没有 ^ 和 $ 时,模式匹配的是一段,不是整条笔记。replace 不会改掉原文。

  • match 什么都没找到时,不要读 null.length
  • 不要指望 replace 就地改掉 note
  • 还要拿去配合 test 反复用的表达式,不要加 g,因为它记得自己停在哪里
  • 真正的句点要写成反斜杠加一个点
  • 不要把这一行读成 lida / mint / 2

记住

  • test 回答 true 或 false
  • /^tea$/ 只接受整条字符串 tea
  • 带 g 的 match 列出每一份,否则返回 null
  • replace 返回一条新字符串
  • 页面这一行是 true / Order: mint

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
5
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部