I want to use the method "exec" in RegExp. I write below code to try to do:
let result = <RegExpExecArray>{};
while (result = expressionCheck.exec(text)) {
let matchIndex = result.index;
let t = result[0].length;
matchRanges.push(new RegRange(matchIndex, t));
}
But it throws error about:
Build:Type 'RegExpExecArray | null' is not assignable to type 'RegExpExecArray'.
I try to modify the loop condition to :
while ((result = expressionCheck.exec(text)) != null) {
It still doesn't work. So how to write the loop condition for this case?
You need to write it like this:
let result;
while ((result = expression.exec(text)) !== null) {
let matchIndex = result.index;
let t = result[0].length;
matchRanges.push(new RegRange(matchIndex, t));
}
Why the original does not work:
The original code declared result
to be of type RegExpExecArray
. This type is not compatible with the return type of exec
which is RegExpExecArray | null
. In spite of the narrowing, via !== null
, the code will still assign null
to result
. That is why it is an error.
You can also write it in the following fashion.
for (let result = expression.exec(text); result !== null; result = expression.exec(text)) {
const matchIndex = result.index;
const t = result[0].length;
matchRanges.push(new RegRange(matchIndex, t));
}
I found String.prototype.matchAll
much more readable, because I can destructure it:
const [[group1, group2]] = [...text.matchAll(expressionCheck)];
MDN recommends it as an alternative and here are the docs.
I wanted to capture hours and minutes from below string
18h:20m
So, I used following expression
const [, hours, minutes] = /^(\d+)[:h -]\s?(\d+)m?$/.exec(string) || ['', '', ''];
You can customize it based on the number of matches you are capturing.
Note: exec() will return all your matches as string type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With