Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight a part of text in textarea

Tags:

Is there a way to highlight a part of text in text-area?

Say, the text is Hi @twitter @twitpic and now I would like to highlight @twitter and @twitpic only and not Hi. Is that possible?

This has to happen on the fly.

PS: I don't want to use iFrame

Thanks in advance

like image 658
Basavaraj Metri Avatar asked Dec 11 '13 11:12

Basavaraj Metri


People also ask

How do you highlight text in input?

For selecting the content of an input (with highlight), use: el. select() . For css manual highlight, see @HashemQolami answer.

How do you highlight a text box in HTML?

Highlight using the HTML5 <mark> tag If you are working on an HTML5 page, the <mark> tag can quickly highlight text. Below is an example of the how to use the mark tag and its result. If your browser supports the <mark> tag, "highlighted text" should have a yellow background.

Can we use value attribute in textarea?

<textarea> does not support the value attribute.


2 Answers

Use setSelectionRange method on that text

Sample code:

<body>     <section>         <textarea id="textarea"></textarea>         <button id="hgh">Hightlight @twiiter</button>     </section>      <script>          window.onload = function () {              var textarea = document.getElementById("textarea");             var checkError = document.getElementById("hgh");              checkError.addEventListener("click", function () {                  var index = textarea.innerText.indexOf("@twitter");                 if( index >= 0)                     textarea.setSelectionRange(index, index + 8);             });         }      </script> </body> 
like image 92
Abhishek Kargawal Avatar answered Sep 21 '22 10:09

Abhishek Kargawal


without wrapping a tag around the specific words, you cannot highlight it (or as i said, at least I have no idea how to). but if there is no problem with wrapping tags, you should use regEx.

for words starting with @ :

replace(/@([^ ]+)/g, '<span class="atsign">@$1</span>'); 

and for the words starting with # :

status.replace(/#([^ ]+)/g, '<span class="hashtag">#$1</span>'); 

check this fiddle

EDIT: you can replace

var status = 'I tweeted something #one #two @three @four'; 

with

var status = $('#phrase').text(); 
like image 30
Payam Shakibafar Avatar answered Sep 21 '22 10:09

Payam Shakibafar