Skip to content

Instantly share code, notes, and snippets.

@niharsawant
Last active October 11, 2015 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niharsawant/3937012 to your computer and use it in GitHub Desktop.
Save niharsawant/3937012 to your computer and use it in GitHub Desktop.
URL Parser using Javascript
function urlify(input) {
var regex = /(https?:\/\/[^\s]+)/g;
return input.replace(regex, function (url){
// Whitelist for last character of URL (Accept other than Letters, numbers and underscore)
var lastCharRegex = /[^\w]$/;
var lastChar = '';
// Check if URL ends with and special characters (such as , . - ! ? etc)
if(lastCharRegex.test(url)) {
// Check if last special character is either #, ? or / if it is then replace it with empty space
// as these characters hold no meaning in URL
lastChar = url[url.length-1].replace(/['#', '?', '\/']/, '');
// Trim special character from URL occured on last position
url = url.replace(lastCharRegex, '');
}
return '<a "href="' + url + '">'+ url + '</a>' + lastChar;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment