iT邦幫忙

0

JS 文章網址自動置換

  • 分享至 

  • twitterImage

目前用AJAX取資料庫資料後,針對有網址的部分做處理

http://www.youtube.com/embed/... > 嵌入影片
http://...jpg > 顯示圖片
http://... > 變超鏈結

以下只能抓到圖片網址,單純網址沒反應 > <

msg.replace(/(((http|https):\/\/[^\<\s]+)(\.(jpg|png|gif))?)/gi, '<a href="'+( "$4" ? "$1" : "$2" )+'" target="_blank">'+( "$4" ? '<img src="$1">' : "$2" )+'</a>');
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

3
dragonH
iT邦超人 5 級 ‧ 2019-06-23 17:27:11

codepen

阿你的 regex 就是只抓 .jpg .png .gif

結尾的阿

當然只能抓到圖片網址

不懂你說的單純網址是什麼

阿圖片網址你要轉成 youtu.be 的用意是...?

ufoer168 iT邦新手 5 級 ‧ 2019-06-23 17:37:59 檢舉

http://www.youtube.com/embed/... > 嵌入影片
http://...jpg > 顯示圖片
http://... > 變超鏈結

dragonH iT邦超人 5 級 ‧ 2019-06-23 18:34:57 檢舉

ufoer168

我 codepen 更新了

作法大概就是再新增一個 youtube embed url 的 regex

不符合 圖片 或 youtube embed 的

就是 show 超連結

你可能再試試有無例外

然後其實也不太需要用 replace

用 match 判斷完

就可以了

2
ccutmis
iT邦高手 2 級 ‧ 2019-06-25 00:31:06

參考看看...

<!doctype html>
<html>
<head>
<style>
body{margin:0;padding:0;}
div{background:#333;color:#efefef;padding:1em;}
a:link,a:visited{color:#ffc;text-decoration:none;}
a:hover,a:active{color:#ff6;text-decoration:underline;}
</style>
</head>
<body>
<h3>RAW</h3>
<div id="rawTxt">
段落1  https://ithelp.ithome.com.tw/images/emoticon/emoticon01.gif 段落1<br/>
段落2  https://www.youtube.com/embed/4ch7FsVIzYQ
 段落2<br/>
段落3  https://ithelp.ithome.com.tw/questions/10194203#answer-356568 段落3<br/>
段落4  https://www.youtube.com/embed/h14TXyxNYfg 段落4<br/>
段落5  https://images.squarespace-cdn.com/content/v1/5c6256602727be14c54ef9a9/1551667843375-62Y1472FR9470JA0XP3X/ke17ZwdGBToddI8pDm48kBhs0kXmJu3pAC_LFF99rKVZw-zPPgdn4jUwVcJE1ZvWhcwhEtWJXoshNdA9f1qD7eaDBaxyzPPG4B3J3_Z93rYLky5fjRrZeLmMK3F2aytfjfg4x4lXesDnM4MUpb-Vdw/icon+twitter+round+120+PNG.png 段落5<br/>
段落6  https://ithelp.ithome.com.tw/ 段落6<br/>
</div>
<h3>FIX</h3>
<div id="fixTxt"></div>

<script>
var myTxt=document.getElementById('rawTxt').innerHTML;
//假設rawTxt的innerHTML是你從資料庫取出的文章,超連結尾端必須是空白或換行字元(才能決定超連結到哪邊結束)
myTxt=myTxt.replace(/(http|https)(:\/\/)([^\s]*)\s/gi,"<a href='$1$2$3' target='_blank'>$1$2$3</a>").replace(/<a href='([^']*)' target='_blank'>(http|https)(:\/\/)([^\s]*)(.)(gif|png|jpg)<\/a>/gi,"<img src='$2$3$4$5$6' />").replace(/<a href='([^']*)' target='_blank'>(http|https)(:\/\/www.youtube)([^<]*)<\/a>/gi,"<iframe width='300' height='168' src='$2$3$4' frameborder='0' allow='autoplay; encrypted-media' allowfullscreen></iframe>");
//將置換過圖片連結影片的myTxt置入div#fixTxt
document.getElementById('fixTxt').innerHTML=myTxt;
</script>
</body>
</html>

我要發表回答

立即登入回答