简体   繁体   中英

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...

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] ?? '';

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.

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