识别字符串中的url并替换成a标签

376 阅读1分钟
import React from 'react'


interface Props {
  content: string
  className?: string
  defaultContent?: string
}

function useAutoLink(props: Props): React.ReactNode {
  const { content, className, defaultContent = '-' } = props
  if (content) {
  	const regex = /(https?:\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])/gi
    return (
        <div className={className}>
          {content.split(regex).map((word) => {
            const matchs = word.match(regex)
              if (matchs) {
                return (
                	<a href={matchs[0]} target='_blank'>{matchs[0]}</a>
                )
              }
              const words = word.split(/\n/g) // 处理换行
              return words.map((w, i) => (
                <React.Fragment key={i}>
                  {w}
                  {i !== words.length - 1 && (<br />)}
                </React.Fragment>
            ))
          })}
        </div>
    )
   }
    return <div className={className}>{defaultContent}</div>
}

export default useAutoLink

使用react hook