js正则函数test,exec,search,match,replace

24 阅读3分钟

lastIndex: 是RegExp对象属性,表示的是上一次匹配文本之后的第一个字符的位置,即下一次匹配的开始位置。位置从0计算

regexp.test(str)

不加g加g
从头开始查找字符串是否与给出的正则表达式模式相匹配,如果是则返回true,否则返回false。从lastIndex位置查找字符串是否与给出的正则表达式模式相匹配,如果是则返回true,否则返回false。
function testDemo(){ 
    var r, re; // 声明变量。 
    var s = "I"; 
    re = /I/ig; // 创建正则表达式模式。 
    console.log(re.test(s)); // 返回 Boolean 结果。 
    console.log(re.test(s)); 
    console.log(re.test(s)); 
} 
testDemo();

输出结果:
true 
false
true

当第二次调用test()的时候,lastIndex指向下一次匹配所在位置1,所以第二次匹配不成功,lastIndex重新指向0,等于第三次又重新匹配。

regexp.exec(str)

不加g加g
如果 exec() 找到了匹配的文本,则返回一个数组。否则,返回 null。
数组: [匹配的文本,子表达式比配文本1,子表达式匹配文本2,...子表达匹配文本n,index: "匹配文本所在位置",input:“整个被检索的字符串string”]
在RegExpObject的lastIndex属性指定的位置检索string。当exec()找到了与表达式相匹配的文本时,在匹配后,它将把RegExpObject的lastIndex属性设置为匹配文本的最后一个字符的下一个位置。也就是说,可以通过反复调用exec()方法来遍历字符串中的所有匹配文本。当exec()再也找不到匹配文本时,它将返回 null,并把lastIndex属性设置为0。
/\{(.+?)\}/.exec('abc${a}dfdsd${b}ddd')

输出结果:
['{a}', 'a', index:4, input:'abc${a}dfdsd${b}ddd']
let reg = /\{(.+?)\}/;
let str = 'abc${a}dfdsd${b}ddd';
let m = null;
while((m = reg.exec(str)) != null){
  // 每次匹配返回的结果
  console.log(m);
  // 每次匹配返回的lastIndex
  console.log(reg.lastIndex);
}
// 最终为0
console.log(reg.lastIndex);

输出结果:
['{a}', 'a', index:4, input:'abc${a}dfdsd${b}ddd']
7
['{b}', 'b', index:13, input:'abc${a}dfdsd${b}ddd']
16
0

str.search(regexp)

不加g加g
返回第一个与regexp相匹配的子串的起始位置,如果没有找到,返回-1。search()方法不执行全局匹配,它将忽略标志g ,忽略regexp的lastIndex属性,总是从字符串的开始进行检索,意味者总是返回str字符串的第一个匹配位置。
'abc${a}dfdsd${b}ddd'.search(/\{(.+?)\}/)

输出结果:
4
'abc${a}dfdsd${b}ddd'.search(/\{(.+?)\}/g)

输出结果:
4

str.match(regexp)

不加g加g
如果 match() 找到了匹配的文本,则返回一个数组。否则,返回 null。
数组: [匹配的文本,子表达式比配文本1,子表达式匹配文本2,...子表达匹配文本n,index: "匹配文本所在位置",input:“整个被检索的字符串string”]
返回所有匹配的子字符串构成的数组,如果没有找到,返回null。
'abc${a}dfdsd${b}ddd'.match(/\{(.+?)\}/)

输出结果:
['{a}', 'a', index:4, input:'abc${a}dfdsd${b}ddd']
'abc${a}dfdsd${b}ddd'.match(/\{(.+?)\}/g)

输出结果:
['{a}', '{b}']

str.replace(regexp,replacetext | function('匹配模式的字符串’,'字表达式匹配的字符串1‘,...'子表达式匹配的字符串n,'匹配字符串的位置','str本身'))

不加g加g
返回一个新的字符串,用replacement替换regexp的第一次匹配的字符串。返回一个新的字符串,用replacement替换regexp的所有匹配的字符串。
const value = '123-234-234-234'
const pattern = '-'
value.replace(pattern, (item, index) => {
	// item 替换元素,index 替换元素的下标
	console.log(item, index)
	return '/'
})

// 输出:
// - 3
// 123/234-234-234