I'm super new to react and I've been asked to help out a react typescript website. At the moment my matches const is returning an Object is possibly 'null'. I've tried making my match constant null but for the life of me I cannot figure out how to work around this not to get this error. Any help would be much appreciated.
case "text":
return (
<div>
{" "}
{note.text.map((content: string, idx: number) => {
const result = [];
const matches = content.match(
/(.*?)(<a href=")?(https?|www)((".*?>.*?<\/a>)|[^\s>]?)*(.*?)/gi
);
if (!!matches) {
matches.forEach((match) => {
let link;
if (/href="/i.test(match)) {
const url = match
.match(/<a href="(.*?)(?=">)/i)[0]
.replace('<a href="', "");
const linkText = match
.match(/(?:<a href=".*?">)(.*)(?=<\/a>)/)[0]
.replace(/(?:<a href=".*?">)/i, "");
link = <a href={url}>{linkText}</a>;
} else {
const url = match.match(/(https?|www)[^\s]*/gi).join("");
link = <a href={url}>{url}</a>;
}
const splitter = match.match(
/(<a href=")?(https?|www)[^\s]*(.*<\/a>)?/gi
)[0];
const paredPlainText = match.split(new RegExp(splitter));
result.push(paredPlainText[0]);
result.push(link);
result.push(paredPlainText[1]);
});
} else {
result.push(content);
}
return <p>{result}</p>;
})}
</div>
);
I'm not fully sure I understand your problem, the description sounds a bit confuse, but I believe you mean that line:
if (!!matches) {
right?
This converts the result of the match call (which can be an array with results or null
) to a bool. Just use
if (matches) {
instead, which checks for a truthy expression ( null
represents a falsy result).
If this answer is not what you are after then please add more description to your question.
Thanks everyone for the response! This was my answer using non-null assertion operator !
after the .match
as below
case "text":
return (
<div>
{" "}
{note.text.map((content: string, idx: number) => {
const result = [];
const matches = content.match(
/(.*?)(<a href=")?(https?|www)((".*?>.*?<\/a>)|[^\s>]?)*(.*?)/gi
);
if (!!matches) {
matches.forEach((match) => {
let link;
if (/href="/i.test(match)) {
const url = match
.match(/<a href="(.*?)(?=">)/i)![0]
.replace('<a href="', "");
const linkText = match
.match(/(?:<a href=".*?">)(.*)(?=<\/a>)/)![0]
.replace(/(?:<a href=".*?">)/i, "");
link = <a href={url}>{linkText}</a>;
} else {
const url = match.match(/(https?|www)[^\s]*/gi)!.join("");
link = <a href={url}>{url}</a>;
}
const splitter = match.match(
/(<a href=")?(https?|www)[^\s]*(.*<\/a>)?/gi
)![0];
const paredPlainText = match.split(new RegExp(splitter));
result.push(paredPlainText[0]);
result.push(link);
result.push(paredPlainText[1]);
});
} else {
result.push(content)
}
console.log(result);
return <p>{result}</p>;
})}
</div>
);
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.