Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to write a function to create tags out of regular links and tags out of image links from the text in a text area.

it works the first time for both, but if i paste an "a href" tag in there, it double links it. it doesn't do the images because of the imageRegex check. any ideas how to get this to work?

keep in mind the textarea could have multiple urls of both types.

$("#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);         
});
like image 686
Chris Brickhouse Avatar asked Dec 16 '11 21:12

Chris Brickhouse


1 Answers

I'm not great at jQuery, but I made a vanillaJS solution to your problem. Check out this fiddle! 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;
like image 111
Joe Thomas Avatar answered Sep 19 '22 17:09

Joe Thomas