I'm quite new to javascript and have an issue on regex
According to this documentation page, the regex.exec() function should return either an array or null if there's no match.
if the match succeeds, the exec() method returns an array and updates properties of the regular expression object. 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.
why then in my code, the result of exec() is either a boolean or 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
).
In other words, x = y !== z
parses as x = (y !== z)
, not (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:
function matchHTMLsymbols(str) { var pattern = /&|<|>|"|' /g, arr; while (((arr = pattern.exec(str)) !== null)) { console.log(arr); } } matchHTMLsymbols('foo<bar"baz&');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.