I am using the following code.
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)[1];
It compiles with the error below.
Object is possibly 'null'.ts(2531).
How can I fix it?
I am using the following code.
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)[1];
It compiles with the error below.
Object is possibly 'null'.ts(2531).
How can I fix it?
I am able to solve this question using non-null assertion operator !
as below
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)![1];
If you don't want to use the !
operator, one other option could be to use the optional operator ?
and use a default value.
const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)?[1] ?? '';
` tag and the text is large enough, BTW. And it will never match `
` tag that contains line breaks in between attributes. That is why regex is not a good idea when parsing HTML. – Wiktor Stribiżew Aug 24 '17 at 07:37