I am new to JavaScript. I am facing a problem with my javascript code. I am trying to use the string replace method to highlight the searched text. But it’s not working. I must be making some mistake. Or may be I am going for the wrong method. Please help. Here is my code:
<html><head>
<style>span.red { color:red; }</style>
<script language="javascript">
function highlightText(htext) {
var str = document.getElementById(htext).value;
//highlight the searched text
str.replace(/([\w]+)/g, '<span class="red">$1</span>');
}
</script></head>
<body><span>Enter a word to search in the paragraph below:</span></br>
<input type="text" id="text-to-find" />
<button onClick="highlightText('text-to-find');">Find</button><hr/><hr/>
<p><b>Type any word from this paragraph in the box above, then click the "Find" button to highlight it red.</b></p></body></html>
getElementById() method finds an item/element by its id, not by a specified string value.
Here’s the fixed code for you, it does what you need it to… You may want to improve upon it though if you’re going to use it in a real life project/website.
Alternatively, you could always use this jQuery plugin to do the job.