论坛首页 Web前端技术论坛

一道关于"/g"笔试题

浏览 3318 次
精华帖 (0) :: 良好帖 (6) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-07-26   最后修改:2013-07-26

正则里“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';
}

 

 

   发表时间:2013-07-26   最后修改:2013-07-26

涨知识了.这前还真不知道这回事.

var reg = /abc/g;

var str = 'abcd';

 

 

reg.test(str); // true

//reg.lastIndex ===3

 

reg.lastIndex=0

reg.test(str); // true

 

0 请登录后投票
   发表时间:2013-07-27  
学习了,以前真不知道。
0 请登录后投票
   发表时间:2013-07-30  
nice
0 请登录后投票
   发表时间:2013-07-31   最后修改:2013-07-31
晕 还有很多参数了  一般都用  /test/ig i=ignore g=global
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics