Features of the global schema in JavaScript regular expressions

  • 2021-01-06 00:25:53
  • OfStack

Returns the Boolean value indicating the status of the global flag (g) used by the regular expression. The default value is false. Read-only. The rgExp parameter is a regular expression object. The global property returns true if the regular expression has the global flag set, otherwise it returns false. Using the global flag indicates that the search operation in the string being looked for will look for all matching entries, not just the first one. This is also known as global matching.

1. I don't know exactly what aspects global shows in javascript, so I have done several tests today:


var str = 'bbaaabb',
  reg = /^b|b$/;
  while(reg.test(str)){
    str = str.replace(reg,'');
    console.log(reg.lastIndex + ":" + str);
  } 

End result:


//0:baaabb
//0:aaabb
//0:aaab
//0:aaa 

But if I change it a little bit


var str = 'bbaaabb',
  reg = /^b|b$/g;
  while(reg.test(str)){
    str = str.replace(reg,'');
    console.log(reg.lastIndex + ":" + str);
  } 

The end result is:


//0:baaab
//0:aaa 

The result shows that global mode, after the match b characters to begin, will continue the b characters at the end of match, thus ignore the middle "|" operator.

JavaScript regular expression in the global mode features to introduce so much, I hope to help you!


Related articles: