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 My function only highlight the First string that it find and dont highlight another strings !!
How can I fix it to find all strings that I type in search .
Here is my Code :
<html>
<head>
<script language="javascript">
function search()
{
var s = document.getElementById("p1").innerHTML
document.getElementById("p1").innerHTML = s.replace(document.getElementById('txt').value , '<span style="color:red">'+document.getElementById("txt").value+'</span>')
}
</script>
</head>
<body>
<input type="text" id="txt" value="search..." onfocus="value=''" />
<input type="button" id="btn" value="search" onclick="search()"/>
<p id="p1">
Type any word from this paragraph in the box above, then click the "Search" button to highlight it red
</p>
</body>
One option is to use
splitandjoinlike so:Here’s a jsFiddle to play with.