Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is possibly 'null' for regex

I am using something like this using RegEx.

 const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)[1];

Expected: Should compile without error.

Actual: [ts] Object is possibly 'null'.

Help me to get of this...

like image 668
Harish Avatar asked Aug 24 '17 07:08

Harish


2 Answers

I am able to solve this question using non-null assertion operator ! as below

const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)![1];
like image 134
Harish Avatar answered Oct 12 '22 16:10

Harish


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] ?? '';
like image 29
user023 Avatar answered Oct 12 '22 15:10

user023