目录
在 WHAT - ECMAScript 正则表达式系列(一)中,我们介绍了正则表达式字面量和 String 对象的正则方法。
今天我们将介绍一下这些 API 的具体使用。
一、正则表达式字面量
正则表达式对象有一些方法可以用于执行匹配、替换和其他操作。以下是正则表达式对象常用的方法:
1. exec(str)
在指定字符串中执行正则表达式匹配,返回匹配结果的数组。如果没有匹配到,则返回 null。
const regex = /\d+/g;
const str = 'abc123def456ghi';
console.log(regex.exec(str)); // 输出: ["123", index: 3, input: "abc123def456ghi", groups: undefined]
console.log(regex.exec(str)); // 输出:['456', index: 9, input: 'abc123def456ghi', groups: undefined]
2. test(str)
这个好理解,判断指定字符串是否匹配正则表达式,返回布尔值。
const regex = /\d+/g;
const str = 'abc123def456ghi';
console.log(regex.test(str)); // 输出: true
二、String 对象
String 对象提供了多个方法用于正则表达式的匹配和搜索,包括 match()
、search()
、replace()
、split()
等。其中 replace 相当常用。
1. match
match(pattern)
用于在字符串中查找一个或多个与正则表达式匹配的文本,并返回一个包含匹配结果的数组。如果未找到匹配项,则返回 null。
const regex = /\d+/g;
const str = 'abc123def456ghi';
console.log(str