Javascript and Regular Expressions: Add hyperlinks to user text

Following the Power of PHP tutorial on adding hyperlinks to text that has been input by a user, I thought it would be fun to do the same in Javascript. I haven't done a walkthrough this time but instead have commented the file. Cut and paste it into a text file saved with the .html extension and have a look.

<html>
<body>
<script>
function addHyperLinksToText() {

//Load the contents of the textarea into a variable when the function is used
var a = document.getElementById('field1').value;

//Define the pattern of the Regular Expression
var patterns = /(http:\/\/|https:\/\/|)([a-zA-Z0-9\-\.]+\.)
(com|co.uk|org.uk|org|net|mil|edu)/gi;

//Make the replacement of all text fitting the pattern
var livetext = a.replace(patterns, "<a href='$1$2$3'>$1$2$3</a>");

//Place this text into the desired place on the page using the ID element
document.getElementById('field2').innerHTML=livetext;
}</script>

Enter your text here:<br />
<textarea type="text" id="field1" value=" " rows=10></textarea>
<br /><br />
Result<p id="field2"></p>
<br /><br />
<button onclick="addHyperLinksToText();">Add HyperLinks</button><br />
<i>Click the button to add hyperlinks to text that is written as a link e.g. www.gylphi.co.uk or sketchytech.blogspot.com or http://www.gylphi.com</i>
</body>
</html>


Comments