---
title: "一道关于\"/g\"笔试题"
author: "zhouyrt"
date: "2013-07-26T07:13:19Z"
tags: []
categories: ["Web前端"]
slug: "g"
draft: false
lastmod: "2013-07-26T07:13:19Z"
id: 1913785
url: "https://snandy.iteye.com/blog/1913785"
---

正则里“g”表示全局(global)的意思，比如当替换字符串时，如果正则不加g，则只替换一次。

```
str = 'hello, jack, hello, lily';
reg = /hello/;
res = str.replace(reg, 'hi');
console.log(res); // 'hi, jack, hello, lily'
```

第二个hello未被替换，正则reg换成“/hello/g”后则全部替换。

 

“g”还有一个作用是它会记录上次匹配时的位置(lastIndex)。这道题如下

```
var reg = /abc/g;
var str = 'abcd';
reg.test(str);
reg.test(str);
```

两次test的结果分别是什么？ 相信不少人会迷惑。

 

这种情况Perl里也会发生

```
use 5.012;
 
my $str = 'abcd';
if ($str =~ /abc/g) {
  say 'true';
} else {
  say 'false';
}
if ($str =~ /abc/g) {
  say 'true';
} else {
  say 'false';
}
```

对于不同的正则对象，JS中会从字符串重新开始，因此以下两次输出都是true。

```
reg1 = /ab/g;
reg2 = /cd/g;
str = 'abcd';
console.log(reg2.test(str));
console.log(reg1.test(str));
```

但Perl中第二次却是false，因为它记住了上次匹配的位置。从字符d后再去匹配ab就匹配不上了。

```
use 5.012;
 
my $str = 'abcd';
if ($str =~ /cd/g) {
    say 'true';
} else {
    say 'false';
}
if ($str =~ /ab/g) {
    say 'true';
} else {
    say 'false';
}
```