---
title: "js 正则表达式的怪异"
author: "hangzhoujava"
date: "2017-05-10T23:34:01Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2017-05-10T23:47:18Z"
id: 2373702
url: "https://hangzhoujava.iteye.com/blog/2373702"
---

看例子吧

 

```
var reg = new RegExp("abc","gi");
console.log(reg.test("abc"));   
console.log(reg.test("abc"));  
console.log(reg.test("abc"));   
console.log(reg.test("abc"));
console.log(reg.test("abc"));   
console.log(reg.test("abc"));
console.log(reg.test("abc"));   
console.log(reg.test("abc"));
```

 惊奇的发现打印结果不一样啊

解决办法有3种 

1 

```
var reg = new RegExp("abc","i");  
console.log(!!reg.match("abcd"));     
console.log(!!reg.match("abcd"));    
console.log(!!reg.match("abcd"));    
console.log(!!reg.match("abcd"));     
console.log(!!reg.match("abcd"));    
console.log(!!reg.match("abcd"));     
console.log(!!reg.match("abcd"));    
console.log(!!reg.match("abcd")); 
```

 

  2 

```
var reg = new RegExp("abc","gi");
reg.lastIndex=0;console.log(reg.test("abc"));   
reg.lastIndex=0;console.log(reg.test("abc"));  
reg.lastIndex=0;console.log(reg.test("abc"));   
reg.lastIndex=0;console.log(reg.test("abc"));
reg.lastIndex=0;console.log(reg.test("abc"));   
reg.lastIndex=0;console.log(reg.test("abc"));
reg.lastIndex=0;console.log(reg.test("abc"));   
reg.lastIndex=0;console.log(reg.test("abc"));
```

 3

  

```
var reg = new RegExp("abc","gi");
var reg = new RegExp("abc","gi");  
console.log(!!'abc'.match(reg)); 
console.log(!!'abc'.match(reg)); 
console.log(!!'abc'.match(reg)); 
console.log(!!'abc'.match(reg)); 
console.log(!!'abc'.match(reg)); 
console.log(!!'abc'.match(reg)); 
```