Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight specific text in TextArea

I need to simulate a find and replace function in my webpage using javascript, no matter with find and replace, but the problem is how to highlight the matched search results inside the textArea before replacing them. I tried to replace matched results with with Bold Tag but it doesn't work because the textArea don't understand HTML tags.

I have used the following code:

function findMyText(searchTxt) {

 var textAreaTxt = "";

 textAreaTxt = document.getElementById("myTxtAreaID").value;
 var match = new RegExp(searchTxt, "ig");     
 var boldText = '<B>' + searchTxt+ '<\/B>';
 var replaced = textAreaTxt .replace(match, boldText);

 document.getElementById("myTxtAreaID").value= replaced;
}

is there any other way to highlight search results in textArea , or how to make textArea understand HTML Tags

Thanks in advance

like image 521
George Avatar asked Sep 20 '11 13:09

George


2 Answers

t = document.getElementById("myTxtAreaID");
l = t.value.indexOf(searchText);
if(l!=-1){
t.selectionStart = l;
t.selectionEnd = l+searchText.length
}

What that code does is find the beginning of the found text and set the selectionStart and selectionEnd values for the textarea. That simply selects the text as if the user had selected the text himself. Working demo here

like image 144
Some Guy Avatar answered Oct 19 '22 17:10

Some Guy


I think the only possible ways to do that are:

  • use javascript canvas drawing to highlight text inside the textarea (?? quite complex i think)
  • use a "fake" textarea, built using an iframe, like what wysiwyg editors (ckeditor, tinymce, ..) do
like image 37
redShadow Avatar answered Oct 19 '22 19:10

redShadow