LoginSignup
8
4

More than 3 years have passed since last update.

URLをリンク化するJavascript (jQuery) 【正規表現】

Last updated at Posted at 2020-08-19

結論

URLをリンクに置き換えるコード
// 1. 正規表現(httpから始まる文字列を判定)
var exp = /((?<!href="|href='|src="|src=')(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

// 2. 要素1の中にあるURLをリンクに置き換える
$('要素1').html($('要素1').html().replace(exp, "<a href='$1'>$1</a>"))

1. 正規表現でURL部分を判定する

正規表現
var exp = /((?<!href="|href='|src="|src=')(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

*aタグの中のhref属性とimgタグのsrc属性のURLは除外

2. replaceでhtmlの置き換え

文章内のURLをリンクに変換
$('要素1').html($('要素1').html().replace(exp, "<a href='$1'>$1</a>"))

*aタグには target="_blank" rel="noopener" を追加した方が良いでしょう。

何か間違いなどございましたら、ご指摘頂けますようお願いいたしますm(_ _)m

8
4
1

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
8
4