Reputation: 15
How can I highlight hyperlinks in textarea. I have created a tag as shown below
<textarea
class="textarea"
name="input_note"
id=""
cols="30"
rows="10"
></textarea>
let's say this input field is used to take a note and saves there(more like a google keep). so when the user inputs any 'links' in the input field, the links are shown as plain text instead of hyperlink. The link is also not highlight as normally has.
---input field I have saved a note with the link- 'https://stackoverflow.com/' but when the note is displayed
> https://stackoverflow.com/
plain text is displayed and not clickable.
Upvotes: 1
Views: 1709
Reputation: 685
This code should work. I had to replace the textarea with div because its impossible to do what you want in textarea but I gave it styling so that it looks just like a textarea.
function linkify(inputText) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
if (inputText.indexOf("<a ")) {
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<div contentEditable="false" style="display: inline-block; padding: 5px;"><a href="$1" target="_blank">$1</a></div>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<div contentEditable="false" style="display: inline-block; padding: 5px;"><a href="http://$2" target="_blank">$2</a></div>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<div contentEditable="false" style="display: inline-block; padding: 5px;"><a href="mailto:$1">$1</a></div>');
} else {
replacedText = inputText;
}
alert(replacedText)
return replacedText;
}
.textarea {
border: 1px solid gray;
min-height: 50px;
/* if you want Flexible textarea/div then give min-height instead of height */
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
font-size: 15px;
color: #000;
}
<div class="textarea" name="input_note" id="textarea" cols="30" rows="10" contenteditable onblur=" var text = document.getElementById('textarea').innerHTML;var text = linkify(text);document.getElementById('textarea').innerHTML = text;"></div>
Upvotes: 2