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?

1
  • Maybe look a RegExp (Regular Expressions) Commented Apr 26, 2014 at 19:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly the information I was looking for. I wasnt aware of "escaping user data"
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>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.