Jonathan Coe
Jonathan Coe

Reputation: 1485

Replacing an anchor with link & truncated value

I have a javascript function that I use to detect and replace links with an anchor (html). However, the problem is that some people paste in massive links that cause page elements to overlow, which breaks the page (typically).

Does anyone know a simple way to combine the following two functions into one that provides an anchor tag with a truncated version of the link inside it?

IE converting

http://Superlonglink

Into

<a href="http://Superlonglink">http://Super...</a>

Using a combination of the following functions:

Function to replace links with anchors:

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
}

Function to truncate a string:

String.prototype.trunc = function(n){
      return this.substr(0,n-1)+(this.length>n?'':'');
};

I've been playing around with this for a while, however I'm finding my understanding of regex with javascript is a bit limited

Upvotes: 0

Views: 495

Answers (2)

epascarello
epascarello

Reputation: 207501

Use a function inside the replace so you can manipulate it.

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,
        function (href) {
            var partial = href.length<10 ? href : href.substring(0,10) + "...";
            return "<a href='" + href + "' target='_blank'>"+ partial + "</a>"});
}



replaceURLWithHTMLLinks("http://www.example.com/IAMAVERYLONGLINKWITHMORESTUFF");

jsfiddle

Upvotes: 1

Will
Will

Reputation: 20235

function replaceURLWithHTMLLinks(text, maxlen) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, function( link ) {
        return '<a href="' + link + '" target="_blank">' +
            (link.length > maxlen ? link.substring( 0, maxlen ) + "..." : link) + '</a>'
    });
}

DEMO: http://jsfiddle.net/84Le9/2/

Upvotes: 1

Related Questions