将网址转换为html <a> tag and image url to <img/> tag with javascript regular expressions</a>

时间:2011-12-16 21:01:26

标签: javascript jquery regex

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

它首次适用于两者,但如果我在其中粘贴“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);         
});

1 个答案:

答案 0 :(得分: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;