extract URLs from string

this will match almost every thing you need, even short urls!

by Amged Osman

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <div id="debug"></div>

JavaScript

var string = 'j.mp/13JTbZm  hellp http://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript';
var reg = /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi;

var matches = [], found;
while (found = reg.exec(string)) {
    matches.push(found[0]);
    reg.lastIndex = found.index+1;
}

jQuery.each(matches, function(key , val) {
jQuery('#debug').append("<br />" +
  '<div class="alert alert-success alert-dismissible fade in" role="alert">' +
 '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
 '<span aria-hidden="true">&times;</span></button>' +
 '<strong>Key:</strong> ' + key + ' <strong>val:</strong> ' + val +
  '</div>');
});
//alert(matches);