Is there an simple way of turning a string from
Then go to http:/example.com/ and foo the bar!
into
Then go to <a href="http://example.com">example.com</a> and foo the bar!
in Javascript within an existing HTML page?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes. The simplest way is to use a regular expressions to substitute things that look like a link for their linked equivalents. Something like:
(my RegEx is a little rusty, so you may need to play with the syntax). This is just a simple case. You need to be wary of script injection here (for example if I have
http://"><script>doevil()</script>). One way to work around this is by using a link building function:Where
buildLink()can check to make sure the URL doesn’t contain anything malicious.However, the RegEx-innerHTML method will not perform very well on large bodies of text though, since it tears down and rebuilds the entire HTML content of the node. You can achieve this with DOM methods as well:
splitText()method to split the node into 3: before, link, after<a>node with thehrefthat’s the same as the linkinsertBefore()to insert this<a>node before the linkappendChild()to move the link into the<a>node