Created
November 7, 2018 19:57
-
-
Save juanbrusco/413b793c69452d591ddc0b4a3ea57be6 to your computer and use it in GitHub Desktop.
Transform Text To Link - React + Js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
convertTextToUrl(text) { | |
let replacedText = ''; | |
if (text != '') { | |
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; | |
var text1 = text.replace(exp, "<a href='$1' target='_blank'>$1</a>"); | |
var exp2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; | |
const node = this.myRefLink.current; | |
if (node != null) { | |
node.innerHTML = text1.replace(exp2, '$1<a href="http://$2" target="_blank">$2</a>'); | |
} | |
return ''; | |
} | |
return replacedText; | |
} | |
//html | |
const detailText = this.convertTextToUrl(this.state.text); | |
<p ref={this.myRefLink}> | |
{detailText} | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment