From 01b0e12ba27b5069248fd09235e9a7143915ee30 Mon Sep 17 00:00:00 2001 From: Irvin Date: Wed, 16 Feb 2022 02:02:49 +0800 Subject: remove `notranslate` class in zh-CN --- .../reference/global_objects/string/matchall/index.html | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'files/zh-cn/web/javascript/reference/global_objects/string/matchall') diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html index f2344f6f79..d11d23265e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll

语法

-
str.matchAll(regexp)
+
str.matchAll(regexp)

参数

@@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll

matchAll 出现之前,通过在循环中调用 regexp.exec() 来获取所有匹配项信息(regexp 需使用 /g 标志):

-
const regexp = RegExp('foo[a-z]*','g');
+
const regexp = RegExp('foo[a-z]*','g');
 const str = 'table football, foosball';
 let match;
 
@@ -54,7 +54,7 @@ while ((match = regexp.exec(str)) !== null) {
 
 

如果使用 matchAll ,就可以不必使用 while 循环加 exec 方式(且正则表达式需使用 /g 标志)。使用 matchAll 会得到一个迭代器的返回值,配合 for...of, array spread, 或者 {{jsxref("Array.from()")}} 可以更方便实现功能:

-
const regexp = RegExp('foo[a-z]*','g');
+
const regexp = RegExp('foo[a-z]*','g');
 const str = 'table football, foosball';
 const matches = str.matchAll(regexp);
 
@@ -71,14 +71,14 @@ Array.from(str.matchAll(regexp), m => m[0]);
 
 

如果没有 /g 标志,matchAll 会抛出异常。

-
const regexp = RegExp('[a-c]','');
+
const regexp = RegExp('[a-c]','');
 const str = 'abc';
 Array.from(str.matchAll(regexp), m => m[0]);
 // TypeError: String.prototype.matchAll called with a non-global RegExp argument

matchAll 内部做了一个 regexp 的复制,所以不像 regexp.execlastIndex 在字符串扫描时不会改变。

-
const regexp = RegExp('[a-c]','g');
+
const regexp = RegExp('[a-c]','g');
 regexp.lastIndex = 1;
 const str = 'abc';
 Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`);
@@ -89,7 +89,7 @@ Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`);
 
 

matchAll 的另外一个亮点是更好地获取捕获组。因为当使用 match() 和 /g 标志方式获取匹配信息时,捕获组会被忽略:

-
var regexp = /t(e)(st(\d?))/g;
+
var regexp = /t(e)(st(\d?))/g;
 var str = 'test1test2';
 
 str.match(regexp);
@@ -97,7 +97,7 @@ str.match(regexp);
 
 

使用 matchAll 可以通过如下方式获取分组捕获:

-
let array = [...str.matchAll(regexp)];
+
let array = [...str.matchAll(regexp)];
 
 array[0];
 // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
-- 
cgit v1.2.3-54-g00ecf