创建
在JavaScript中,创建正则的方式主要有两种:
- 字面量
- 构造函数RegExp
如下:
const reg1 = /test/ // 字面量方式
const reg2 = new RegExp('test') // 通过构造函数RegExp来创建正则实例
两种创建方式基本相同,但优先使用字面量,因为更简洁。
但如果需要在运行时动态修改正则表达式,那只能通过构造函数RegExp来创建。
现在有个小需求:
在输入框中控制输入的小数点位数,位数是个变量。
// decimal表示位数
let str = '66.666'
const decimal = 2
const reg = new RegExp(`\\d*(\\.?\\d{0,${decimal}})`, 'g')
str = (str.match(reg)[0]) // 66.66
方法
test
test方法返回值是Boolean类型,测试目标文本中是否存在符合正则表达式描述的项。是开发中最常用的方法之一。
search
search方法和test方法有点像,都可用于对目标文本的检索,只是test返回的是Boolean值表示是否找到,而search方法返回的是匹配位置索引,没找到就返回-1
const paragraph = 'The fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const regex = /[^\w\s]/g; // 全局搜索非字母数字下划线和空白符
console.log(paragraph.search(regex)); // 31 匹配了.
exec
exec方法返回的是一个数组或null,在全局模式下,每匹配到一次,lastIndex会被记住,下次再执行exec方法时,会从上次lastIndex位置往后匹配,但如果未匹配到返回null,lastIndex则会被重置为0
let reg = /ab*/g;
let str = 'abbcdefabh'
reg.exec(str) // 返回下标 0
reg.exec(str) // 返回下标 7
reg.exec(str) // null,lastIndex被重置
reg.exec(str) // 返回下标 0
match
match方法检索返回一个字符串匹配正则表达式的结果。当有检索结果返回数组,如果没有检索到则返回null
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
paragraph.match(regex); // ['T', 'I']
如果match方法不传入任何正则表达式,则返回['']
matchAll
matchAll方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。分组之前也说过,是用括号括起来的表达式。
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]); // expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]); // expected output: Array ["test2", "e", "st2", "2"]
这里存在三个子组:e st(\d?) \d?,所以与它们匹配的都会返回。
replace
用于替换文本某些字符,JavaScript中没有replaceAll方法,replace全局模式匹配就派上了用场。
const p = 'The fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// "The fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
p.replace(regex, 'ferret')
// The fox jumps over the lazy ferret. If the dog reacted, was it really lazy?
split
split是根据定义的规则进行拆分成数组,在操作字符串中很常用。
const str = 'here, 2 cats.';
const words = str.split(/\d+/);
console.log(words) // ['here, ', ' cats.']