rbyrne
rbyrne

Reputation: 193

Find and separate links in JavaScript string

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?

Upvotes: 0

Views: 121

Answers (2)

Lukas Kral
Lukas Kral

Reputation: 997

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

Upvotes: 2

EyasSH
EyasSH

Reputation: 3789

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>");

Upvotes: 1

Related Questions