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
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
I think the only possible ways to do that are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With