[英]Convert url to html <a> tag and image url to <img> tag with javascript regular expressions
我正在嘗試編寫一個函數,以從常規鏈接中創建標簽,並從文本區域中的文本中從圖像鏈接中創建標簽。
它對兩者都第一次起作用,但是如果我在其中粘貼“ a href”標簽,則會對其進行雙重鏈接。 由於imageRegex檢查,它不執行圖像。 任何想法如何使它工作?
請記住,textarea可能具有兩種類型的多個URL。
$("#message").blur(function() {
var imageRegex = /\.(png|jpg|jpeg|gif)$/;
var s = $(this).val().replace(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim, function(str) {
if (str.match(imageRegex)) {
return('<img src="' + str + '" />');
} else {
return('<a href="' + str + '">' + str + '</a>');
}
});
$(this).val(s);
});
我不太擅長jQuery,但是我為您的問題提供了vanillaJS解決方案。 看看這個小提琴! http://jsfiddle.net/dv0s5onj/
var yourString=document.getElementById('message').innerHTML;
var count=0;
var urls=yourString.match(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim);
// Make an array of urls
urls.forEach(function(v,i,a){
var n = yourString.indexOf(v,count); //get location of string
if(v.match(/\.(png|jpg|jpeg|gif)$/)===null){// Check if image
// If link replace yourString with new anchor tag
yourString = strSplice(yourString,n,v.length,'<a href="'+v+'">'+v+'</a>');
count += (v.length*2)+16;// Increase count incase there are multiple of the same url.
}else{
// If link replace yourString with img tag
yourString = strSplice(yourString,n,v.length,'<img src="'+v+'" height="120px;" width="120px;"/>');
count += v.length+14;// Increase count incase there are multiple of the same url.
}
});
// A function to splice strings that I found on another StackOverflow Question.
function strSplice(str, index, count, add) {
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
//Replace the value of your element with your string
document.getElementById('message').innerHTML=yourString;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.