fix #69
This commit is contained in:
		
							parent
							
								
									e66664e626
								
							
						
					
					
						commit
						a1aaf9e2be
					
				@ -98,9 +98,7 @@
 | 
			
		||||
	console.log(reg.test(str)); // 打印结果:true
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 两种方式的对比
 | 
			
		||||
 | 
			
		||||
**以上两种方式的对比**:
 | 
			
		||||
### 以上两种方式的对比
 | 
			
		||||
 | 
			
		||||
- 方式一:使用构造函数创建时,更加灵活,因为参数中还可以传递变量。
 | 
			
		||||
 | 
			
		||||
@ -116,6 +114,54 @@
 | 
			
		||||
 | 
			
		||||
上面这两行代码的作用是等价的。
 | 
			
		||||
 | 
			
		||||
### 避坑指南:全局匹配 g 慎用test()方法
 | 
			
		||||
 | 
			
		||||
对于非全局匹配的正则表达式,`test()`只会检测**是否存在某个目标字符串**(只要存在就为 true),多次检测的结果都相同。例如:
 | 
			
		||||
 | 
			
		||||
```javascript
 | 
			
		||||
const reg = /test/;
 | 
			
		||||
const str = '_test_test';
 | 
			
		||||
 | 
			
		||||
reg.test(str) // true
 | 
			
		||||
reg.test(str) // true
 | 
			
		||||
reg.test(str) // true
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
重点来了。
 | 
			
		||||
 | 
			
		||||
当设置全局标志 `/g` 时,一旦字符串中还存在匹配,test() 方法都将返回 true,同时匹配成功后将把 `lastIndex` 属性的值**设置为上次匹配成功结果之后的第一个字符所在的位置**,下次匹配将从 `lastIndex` 指示的位置开始;匹配不成功时返回 false,同时将 lastIndex 属性的值重置为 0。
 | 
			
		||||
 | 
			
		||||
举例:(很重要的例子,看仔细)
 | 
			
		||||
 | 
			
		||||
```javascript
 | 
			
		||||
const reg = /test/g;
 | 
			
		||||
const str = '_test_test';
 | 
			
		||||
 | 
			
		||||
console.log(reg.test(str)); // true
 | 
			
		||||
console.log(reg.lastIndex); // 5
 | 
			
		||||
 | 
			
		||||
console.log(reg.test(str)); // true
 | 
			
		||||
console.log(reg.lastIndex); // 10
 | 
			
		||||
 | 
			
		||||
console.log(reg.test(str)); // false
 | 
			
		||||
console.log(reg.lastIndex); // 0
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**总结**:
 | 
			
		||||
 | 
			
		||||
全局匹配模式`g`一般用于 `exec()`、`match()`、`replace()`等方法。
 | 
			
		||||
 | 
			
		||||
全局匹配模式`g`如果用于test()方法会有问题。因为g模式会生成一个`lastindex`参数来存储匹配最后一次的位置。
 | 
			
		||||
 | 
			
		||||
参考链接:
 | 
			
		||||
 | 
			
		||||
- [JS正则表达式全局匹配的那些坑](https://juejin.im/post/5de9bd5fe51d45582c27b6f3)
 | 
			
		||||
 | 
			
		||||
- [javascript正则全局匹配g慎用test方法](https://blog.csdn.net/Leolu007/article/details/8576490)
 | 
			
		||||
 | 
			
		||||
- [issues](https://github.com/qianguyihao/Web/issues/69)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
## 正则表达式的简单语法
 | 
			
		||||
 | 
			
		||||
### 检查一个字符串中是否包含 a或b
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user