简体   繁体   中英

TypeError: Cannot read property '0' of null in react

I've got a typescript app that I've been asked to help with. At the last minute the website owner wanted to change the front end so the links are clickable. Only issue is they data is entered in the backend as a normal anchor href tag. So I've been working on a work around because i can't use that innerhtml method for security reasons.

  switch (note.kind) {
    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>
      );

This is my code but the only issue is I'm running into TypeError: Cannot read property '0' of null on the.match methods. Any help would be much appreciated Thank you!

You should make sure there was a match from regex and it isn't null

const splitter = match.match(/(<a href=")?(https?|www)[^\s]*(.*<\/a>)?/gi);

if (splitter && splitter.length) {
    const paredPlainText = match.split(new RegExp(splitter[0]));
    const [firstParedPlainText, secondParsedPlainText] = paredPlainText || [null, null];
    if (firstParedPlainText) result.push(firstParedPlainText);

    result.push(link);
    if (secondParsedPlainText) result.push(secondParsedPlainText);
}

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