Last active
October 4, 2015 01:32
-
-
Save Lin4ipsum/60083378177d6991d28f to your computer and use it in GitHub Desktop.
Turn comment urls into clickable links
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<title>Linkify Comment Urls</title> | |
<style> | |
body { | |
background-color: #F1F1F1; | |
font-family: Helvetica; | |
} | |
textarea { | |
display: block; | |
margin: 0 auto; | |
} | |
button { | |
background-color: #EBF568; | |
border-radius: 5px; | |
display: block; | |
font-weight: bold; | |
margin: 0 auto; | |
padding: 5px 15px; | |
} | |
.commentContainer { | |
padding-top: 10px; | |
} | |
.buttonContainer { | |
padding-top: 10px; | |
padding-bottom: 10px; | |
} | |
.formattedCommentForm { | |
text-align: center; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="commentContainer"> | |
<textarea name="" id="" cols="30" rows="10" class="commentForm">This is a great article. You should check out https://www.nytimes.com or www.imgur.com for more articles like this. | |
</textarea> | |
<div class="buttonContainer"> | |
<button class="submit">Submit</button> | |
</div> | |
<div class="formattedCommentForm"></div> | |
</div> | |
<script> | |
$('.submit').click(function() { | |
var comment = $(".commentForm").val(); | |
$(".formattedCommentForm").html(makeUrlsLinks(comment)); | |
}); | |
function makeUrlsLinks(comment) { | |
return comment.split(" ").map(linkIfUrl).join(" "); | |
} | |
function linkIfUrl(word) { | |
if(hasUrl(word)) { word = urlify(word);} | |
return word; | |
} | |
function hasUrl(word) { | |
var urlRegex = /(www|http|https?:\/\/[^\s]+)/g; | |
return urlRegex.test(word); | |
} | |
function urlify(text) { | |
return "<a href='" + addHttp(text) + "'>" + text + "</a>"; | |
} | |
function addHttp(url) { | |
return url.search("http") === -1 ? "http://" + url : url | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment