如何将句子中的某些单词转换为链接?

发布于 2025-01-12 09:46:50 字数 822 浏览 2 评论 0原文

这是使用 React 在字符串中创建链接的示例。我发现的大多数例子都是我操纵 dom 的,所以经过一番折腾后,我想出了如何做到这一点。

function profile() {
  const hashtagRegex = /\B(\#[a-zA-Z]+\b)(?!;)/gm;
  const { fullName, userName, image, bio } = userProfileData;
  const bioMatch = bio && bio.match(hashtagRegex);
  const editbio = bio && bio.split(" ");
  bioMatch &&
    editbio.map((word, index) => {
      if (word.match(hashtagRegex)) {
        editbio[index - 1] = editbio[index - 1] + " ";
        editbio[index] = <a href="https://google.com">{word}</a>;
      } else {
        editbio[index] = " " + word;
      }
    });
  return (
    <div className="profile">{editbio}</div>
  );
}

如果您直接向数组索引添加空格,它会将链接转换为 [object][object] ,如果您尝试加入返回,它也会执行相同的操作,因此这对我有用。如果有人有更好的方法,请分享。

This is an example of creating links in a string using react. Most of the examples I found were my manipulating dom so after so messing around I figured out how to do it.

function profile() {
  const hashtagRegex = /\B(\#[a-zA-Z]+\b)(?!;)/gm;
  const { fullName, userName, image, bio } = userProfileData;
  const bioMatch = bio && bio.match(hashtagRegex);
  const editbio = bio && bio.split(" ");
  bioMatch &&
    editbio.map((word, index) => {
      if (word.match(hashtagRegex)) {
        editbio[index - 1] = editbio[index - 1] + " ";
        editbio[index] = <a href="https://google.com">{word}</a>;
      } else {
        editbio[index] = " " + word;
      }
    });
  return (
    <div className="profile">{editbio}</div>
  );
}

If you add spacing directly to the array index it converts the link into [object][object] and if you try to join in the return it does the same so this worked for me. If someone has a better way to do it, please share.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恰似旧人归 2025-01-19 09:46:50

如果您尝试使用 HTML 将网站链接到文本,最简单的方法是

<p><a href="link">word</a></p>

The easiest way to link the website to the text if you are trying to do it with HTML would be

<p><a href="link">word</a></p>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文