iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📌

[React] The Shortest Way to Convert \n to <br>

に公開

The shortest way to convert \n to <br>

Split the text and output the odd-indexed elements as <br> and the even-indexed elements as normal text.
By using () in the regular expression with split, the \n itself is captured, allowing you to accurately identify its position.

export default () => {
  const text = "あいうえお\nかきくけこ\nさしすせそ";
  return <div>{text.split(/(\n)/).map((v, i) => (i & 1 ? <br key={i} /> : v))}</div>;
};

The shortest way to convert URL to <a>

While I'm at it, I'll also leave an example for converting URLs into links.

export default () => {
  const text = "あいうえおhttps://www.yahoo.co.jpかきくけこhttp://google.com/さしすせそ";
  return (
    <div>
      {text.split(/(https?:\/\/[\w!\?/\+\-_~=;\.,\*&@#\$%\(\)'\[\]]+)/).map((v, i) =>
        i & 1 ? (
          <a key={i} href={v}>
            {v}
          </a>
        ) : (
          v
        )
      )}
    </div>
  );
};
GitHubで編集を提案

Discussion