简体   繁体   English

为什么regex.exec()返回类型是布尔值?

[英]Why is regex.exec() return type is a boolean?

I'm quite new to javascript and have an issue on regex 我对javascript很陌生,正则表达式有问题
According to this documentation page, the regex.exec() function should return either an array or null if there's no match. 根据文档页面,regex.exec()函数应返回数组,如果不匹配则返回null。

if the match succeeds, the exec() method returns an array and updates properties of the regular expression object. 如果匹配成功,则exec()方法返回一个数组并更新正则表达式对象的属性。 The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. 返回的数组具有匹配的文本作为第一项,然后是每个与捕获的括号匹配的项,其中包含捕获的文本。 If the match fails, the exec() method returns null. 如果匹配失败,则exec()方法返回null。

why then in my code, the result of exec() is either a boolean or null ? 为什么在我的代码中,exec()的结果是布尔值还是null

function matchHTMLsymbols(str)
  var pattern = /&|<|>|"|' /g;
  var arr;
  while ((arr = pattern.exec(str) !== null)) {
    console.log(arr);
    }
}

Because arr isn't the result of exec , it's the result of !== (which should be either true or false ). 因为arr不是exec的结果,所以是!==的结果(应该为truefalse )。

In other words, x = y !== z parses as x = (y !== z) , not (x = y) !== z . 换句话说, x = y !== z解析为x = (y !== z)而不是(x = y) !== z

You probably meant to write 你可能想写

while ((arr = pattern.exec(str)) !== null) {

instead. 代替。

You should add one pair of parentheses in your while loop: 您应该在while循环中添加一对括号:

 function matchHTMLsymbols(str) { var pattern = /&|<|>|"|' /g, arr; while (((arr = pattern.exec(str)) !== null)) { console.log(arr); } } matchHTMLsymbols('foo<bar"baz&'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM