global 属性 (Regular Expression)

返回布尔值,该值指示使用正则表达式global标志(g)的状态。默认值是false。只读。

语法

rgExp.global

备注

必需的rgExp引用是Regular Expression对象的一个实例。

global属性在为正则表达式设置全局标志时返回true,否则返回false

当使用全局标志时,它将指示一个搜索操作应找到被搜索字符串中的所有模式,而不仅仅是第一个。这也称为全局匹配。

示例

下面的示例演示了global属性的用法。如果将g传递到下面显示的函数中,“the”一词的所有实例都将替换为“a”一词。请注意,不会替换字符串开头的“The”,因为i(忽略大小写)标志未传递到函数。

此函数显示与允许的正则表达式标志关联的属性条件,它们是gim。此函数还显示进行了所有替换的字符串。

function RegExpPropDemo(flag){
  // The flag parameter is a string that contains
  // g, i, or m. The flags can be combined.
  // Check flags for validity.
  if (flag.match(/[^gim]/))
   {
   return ("Flag specified is not valid");
   }
  // Create the string on which to perform the replacement.
  var ss = "The batter hit the ball with the bat ";
  ss += "and the fielder caught the ball with the glove.";
  //Replace "the" with "a".
  var re = new RegExp("the", flag);
  var r = ss.replace(re, "a");   
  // Output the resulting string and the flags.
  var s = "";
  s += "global: " + re.global.toString();
  s += "<br />";
  s += "ignoreCase: " + re.ignoreCase.toString();
  s += "<br />";
  s += "multiline: " + re.multiline.toString();
  s += "<br />";
  s += "Resulting String: " + r;
  return (s);
}
document.write(RegExpPropDemo("g"));

示例

下面是结果输出。

global: true
ignoreCase: false
multiline: false
Resulting String: The batter hit a ball with a bat and a fielder caught a ball with a glove.

必备条件

在以下文档模式中受支持:怪异模式、Internet Explorer 6标准模式、Internet Explorer 7标准模式、Internet Explorer 8标准模式、Internet Explorer 9标准模式、Internet Explorer 10标准模式、Internet Explorer 11标准模式。应用商店应用(Windows 8和Windows Phone 8.1)中也受支持。请参阅版本信息

Applies ToRegular Expression Object

如果你喜欢这篇文章,敬请给站长打赏↑

除特别注明外,本站所有文章均为本站站长原译,转载请注明出处。