0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactで文字列内のURLをaタグにする方法

Posted at

SlackやX(旧Twitter)、LineなどでURLを貼り付けて投稿するとURLの部分がリンクになり、クリックするとそのURLのページを開くことができますが、あれをReactでやる方法です。

「[react-string-replace](URL https://www.npmjs.com/package/react-string-replace)」というライブラリを使うと実現できます。

サンプル

import reactStringReplace from 'react-string-replace';

const text = 'URLをご確認ください。https://www.dabohaze.site よろしくお願いします。'

const Sample = () => {
  return (
    <p>
      {reactStringReplace(text, /(https?:\/\/\S+)/g, (match, i) => (
        <a key={i} href={match} target="_blank">{match}</a>
      ))}
    </p>
  )
}

export default Sample

解説

reactStringReplaceの第一引数の文字列内に第二引数の正規表現にマッチするパターンがあった場合、文字列を置換してくれます。

「match」には正規表現にマッチした文字列が入るので、上記の場合はURLが入るのでそれをhrefと文字列に指定しています。

正規表現にマッチする文字列が複数存在する場合は全て置換してくれますし、正規表現なのでURL以外にも電話番号やハッシュタグなどにも使用できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?