Highlight specific text in TextArea

I need to model the search and replace function on my webpage using javascript, regardless of the search and replace, but the problem is how to highlight matching search results inside textArea before replacing them. I tried replacing the consistent results with a Bold Tag, but it does not work because textArea does not understand HTML tags.

I 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

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

What this code does is find the beginning of the text found and set the selectStart and selectionEnd values ​​for the text field. It simply selects the text as if the user had selected the text. We work a demo here

+8
source

I think the only possible ways to do this are:

  • use javascript-based drawing to select the text inside the text box (quite complicated, I think)
  • use a "fake" text area built using iframe, for example that wysiwyg editors (ckeditor, tinymce, ..) do
+3
source

The text box cannot display htmltags, you need to hide the text box and display the content in a div or iframe. These are the methods used by many wysiwyg editors. Another way could be to use a contentEditable div

+2
source

Source: https://habr.com/ru/post/897686/


All Articles