Last active
October 11, 2015 23:37
-
-
Save niharsawant/3937012 to your computer and use it in GitHub Desktop.
URL Parser using Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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