转换url为html <a>标签和图像url到<img>用javascript正则表达式标记

Convert url to html <a> tag and image url to <img> tag with javascript regular expressions

本文关键字:url javascript img 正则表达式 标签 html 转换 图像      更新时间:2023-09-26

我正试图编写一个函数,从文本区域的文本中创建常规链接的标签和图像链接的标签。

第一次对两个都有效,但如果我在那里粘贴一个"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,但我为您的问题做了一个简单的解决方案。看看这把小提琴!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;