0

I am making a Windows 8 app with HTML + JS and have a field where the user can input some data, when they revisit the page I set a <div> equal to their input. It is possible they may input a URL so I want to convert it to a link. Every example I has read about talks about enclosing it in an tag however when I write the text into the div I use "div.innerText" rather than "div.innerHTML" in case the user wrote incorrect HTML as their data which then causes the app to crash.

Is there anyway I can fail safe against the user entering incorrect HTML and still have hyperlinks in the text?

tymeJV
  • 103,943
  • 14
  • 161
  • 157
rbyrne
  • 193
  • 1
  • 1
  • 12

2 Answers2

2

You need to escape user data first, then replace URLs with links and use innerHTML property to write data into the element

Community
  • 1
  • 1
Lukas Kral
  • 987
  • 13
  • 22
  • Thank you, this is exactly the information I was looking for. I wasnt aware of "escaping user data" – rbyrne Apr 26 '14 at 20:38
1

You can do this to replace a URL to a link using innerHTML.

    // ... first write to element.innerText if you want to then:
    var url_regex = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;
    element.innerHTML = element.innerHTML.replace(url_regex, "<a href=\"$1\">$1</a>");
EyasSH
  • 3,679
  • 22
  • 36