From b0087280f324f005ecac7aa23183046a3d2b1210 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 5 Dec 2018 15:04:49 +0200 Subject: [PATCH] Create AutoLink.md --- snippets/AutoLink.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 snippets/AutoLink.md diff --git a/snippets/AutoLink.md b/snippets/AutoLink.md new file mode 100644 index 000000000..275cfe352 --- /dev/null +++ b/snippets/AutoLink.md @@ -0,0 +1,38 @@ +### AutoLink + +Renders a string as plaintext, with URLs converted to appropriate `` elements. + +Use `String.prototype.split()` and `String.prototype.match()` with a regular expression to find URLs in a string. +Return a `` with matched URLs rendered as `` elements, dealing with missing protocol prefixes if necessary, and the rest of the string rendered as plaintext. + +```jsx +function AutoLink({ text }) { + const delimiter = /((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi; + + return ( + + {text.split(delimiter).map(word => { + let match = word.match(delimiter); + if (match) { + let url = match[0]; + return ( + {url} + ); + } + return word; + })} + + ); +} +``` + +```jsx +ReactDOM.render( + , + document.getElementById('root') +); +``` + + + +