Here is the example for making a search box with a matched case which shows the searched text with the highlighted matches available. You have to paste your paragraph text in the text-area and enter the searching keyword in input box given below the text-area.
The Regex flag/g searches the matched case at the position where the previous match ended.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Searching for strings</title>
<style type="text/css">
#searchSubmit
{
background-color: #ff0;
width: 200px;
text-align: center;
padding: 10px;
border: 2px inset #ccc;
}
.found
{
background-color: #ff0;
}
</style>
<script type="text/javascript">
//<![CDATA[
window.onload=function() {
document.getElementById("searchSubmit").onclick=doSearch;
}
function doSearch() {
// get pattern
var pattern = document.getElementById("pattern").value;
var re = new RegExp(pattern,"g");
// get string
var searchString = document.getElementById("incoming").value;
var matchArray;
var resultString = "<pre>";
var first=0; var last=0;
// find each match
while((matchArray = re.exec(searchString)) != null) {
last = matchArray.index;
// get all of string up to match, concatenate
resultString += searchString.substring(first, last);
// add matched, with class
resultString += "<span class='found'>" + matchArray[0] + "</span>";
first = re.lastIndex;
}
// finish off string
resultString += searchString.substring(first,searchString.length);
resultString += "</pre>";
// insert into page
document.getElementById("searchResult").innerHTML = resultString;
}
//--><!]]>
</script>
</head>
<body>
<form id="textsearch">
<textarea id="incoming" cols="150" rows="10">
</textarea>
<p>
Search pattern: <input id="pattern" type="text" /></p>
</form>
<p id="searchSubmit">Search for pattern</p>
<div id="searchResult"></div>
</body>
</html>
0 Comment(s)