2

Convert the url in CONENT to be clickable and make it shorter.

For example:

Convert the content

Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff

to

Balabala The link is <a href=http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff>http://www.google.com/?aa...</a>
Bruce Dou
  • 4,673
  • 10
  • 37
  • 56
  • 1
    possible duplicate of [How to replace plain URLs with links?](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – icktoofay Sep 23 '11 at 03:24
  • @icktoofay this is a different problem. The url should be shorted. – Bruce Dou Sep 23 '11 at 10:35
  • [`replace`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace) can take a function, which would allow you to truncate the URL. With that said, I think the question is, if not an *exact* duplicate, *very* similar. – icktoofay Sep 24 '11 at 01:28

3 Answers3

0

Something like this may help:

<div id='result'>
</div>
<script>
var content = "The link is http://www.google.com/?q=hello visit it!";
var result = content.replace(/(http:\/\/(www\.)?([^(\s)]+))/, "<a href='$1'>$3</a>");
document.getElementById('result').innerHTML = result;
</script>
derp
  • 2,940
  • 17
  • 16
0

Here is a function that replaces any URLs inside a string with an anchor:

function linkify(str){
    var url = 'http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff';
    return str.replace(/https?\:\/\/\S+/, function(url){
        var shortUrl = url.substring(0, 20) + '...';
        return shortUrl.link(url)
    })
}

linkify("Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff")
// "Balabala The link is <a href="http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff">http://www.google.com/?aaaaabe...</a>"

The "cut" length can be passed as the second argument.

Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
-1

Something like:

len = 15; //set how long of a string you would like to show

url = "http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff";

//if the original url is smaller than or equal to the length than do nothing
//otherwise take the len number of chars and append ... after
shorturl = (url.length <= len) ? url : url.substr(0,len) + "..."; 

link = "<a href='" + url + "'>" + shorturl + "</a>";
Nertim
  • 380
  • 6
  • 15