reactjs 如何使我的代码可以检测到我想要的每个链接

cczfrluj  于 2023-11-18  发布在  React
关注(0)|答案(2)|浏览(112)

所以我想我的React代码来检测每一个链接,就像我输入例如“http://localhost:3000/”它给了我一个格式化的链接,而不是一个纯文本
下面是我的代码:

//Linkify.jsx
import DOMPurify from 'dompurify'
const Linkify = ({ children }) => {
  const isUrl = (word) => {
    const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
    return word.match(urlPattern);
  };

  const addMarkup = (word) => {
    return isUrl(word) ? `<a class="text-blue-500 hover:text-blue-600 transition" href="${word}">${word}</a>` : `<span className="no-underline">${word}</span>`;
  };

  const words = children.split(" ");
  const formatedWords = words.map((w, i) => addMarkup(w));

  const html = DOMPurify.sanitize(formatedWords.join(' '))

  return <span  dangerouslySetInnerHTML={{ __html: html }} />;
};

export default Linkify;

个字符
任何有用的东西

fykwrbwg

fykwrbwg1#

我在codepen中复制了你的代码,它工作得很好,只是URL上的端口,没有顶级域(RegEx没有拾取的顶级域)。
将代码与常规格式的URL一起使用可以正常工作。
Working Codepen Example

import dompurify from "https://esm.sh/dompurify";
import React from "https://esm.sh/react";
import ReactDOM from "https://esm.sh/react-dom";

const Linkify = ({ children }) => {
  const isUrl = (word) => {
    const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
    return word.match(urlPattern);
  };

  const addMarkup = (word) => {
    return isUrl(word)
      ? `<a class="text-blue-500 hover:text-blue-600 transition" href="${word}">${word}</a>`
      : `<span className="no-underline">${word}</span>`;
  };

  const words = children.split(" ");
  const formatedWords = words.map((w, i) => addMarkup(w));

  const html = dompurify.sanitize(formatedWords.join(" "));

  return <span dangerouslySetInnerHTML={{ __html: html }} />;
};

const Test = () => {
  return (
    <div>
      <Linkify>
        Add a URL in here, for example, http://www.google.com/ -- look's good!
      </Linkify>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("app"));

root.render(<Test />);

字符串
欢呼

wbrvyc0a

wbrvyc0a2#

好吧,我找到了我的问题的答案,这里是检测所有链接的代码:

import dompurify from "dompurify";

// detects every link now
const Linkify = ({ children }) => {
  const isUrl = (word) => {
    const urlPattern = /(https?:\/\/[^\s]+)/g;
    return word.match(urlPattern);
  };

  const addMarkup = (word) => {
    return isUrl(word)
      ? `<a class="text-blue-500 hover:text-blue-600 transition" href="${word}">${word}</a>`
      : `<span className="no-underline text-white">${word}</span>`;
  };

  const words = children.split(" ");
  const formatedWords = words.map((w, i) => addMarkup(w));

  const html = dompurify.sanitize(formatedWords.join(" "));

  return <span dangerouslySetInnerHTML={{ __html: html }} />;
};

export default Linkify

字符串

相关问题