Question

Say I have a paragraph of text:

The Northrop Grumman X-47B https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B 
is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based 
operations.

I want to replace the hyperlink within the text and turn it into a real hyperlink. At the same time I want to shorten the wording of the hyperlink to a fixed 20 characters so the text the user would read is shorter e.g.

  • The Northrop Grumman X-47B https://en.wikipedia.org... is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based operations.

So the code of the link within the text might look like this:

<a href="https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B">https://en.wikipedia.org...</a>

I have had a look around and found a few examples but they don't work at all. I would like just a standard JavaScript function to do it. That is, a function which takes in plaintext (not HTML) and can convert the text. Not sure how you would protect against XSS at the same time.

I have a suspicion it will involve a combination of looping through each part of the text, then some regex to find the URL, extract it, then shorten the URL with substr() then replace it into the text somehow. Any idea how to do it?

Thanks for the help.

Was it helpful?

Solution 2

Use this script

<script>
function convertlink(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + geturl(url) + '</a>';
    })

}

function geturl(url){
    if(url.length > 20){
     return url.substr(0,20) + "...";
    } else { 
     return url;
    }
}

var str = "The Northrop Grumman X-47B https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based operations."

alert(convertlink(str));
</script>

OTHER TIPS

Something like this:

$('p').html(function(_,txt) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return txt.replace(exp, function(l) {
        return '<a href="'+l+'">'+l.substr(0,20)+'...</a>'
    }); 
});

FIDDLE

I edited the approved answer to return what you need. This will replace the link text regardless of the link (ie, it's not a link to wikipedia).

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

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top