使用javascript正则表达式将url转换为html <a>标签并将图片网址转换为<img>标签

Chr*_*use 8 javascript regex jquery

我正在尝试编写一个函数,用于从文本区域中的文本中的常规链接和标记中创建标记.

它是第一次为两者工作,但如果我在其中粘贴"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);         
});
Run Code Online (Sandbox Code Playgroud)

Joe*_*mas 2

我不太擅长 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;
Run Code Online (Sandbox Code Playgroud)