Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression - replacing text

Status
Not open for further replies.

y2k1981

Programmer
Aug 2, 2002
773
IE
I've written a basic function that searches in DIV's for text and makes the div visible if a match is found (they're all hidden by default). Now, what I want to do is make the matching text bold by wrapping it in <B> tags. But I can't seem to get it right. Here's what I've got so far:
Code:
function doMySearch()
{
var searchObj2 = document.forms['search'].elements['searchString'].value;
var searchString = new RegExp(searchObj2,"i");

var myArray = document.getElementsByTagName("div");
for(var i = 0; i < myArray.length; i++)
{
var searchText = myArray[i].innerText;
//alert(searchString);
var searchResult = searchText.match(searchString);
if(searchResult)
	{
		//searchResult.replace("test");
		myArray[i].style.display='block';
	} else { 
		myArray[i].style.display='none';
  }
 }
}
I've used an alert where I've commented out searchResult above to tell me what it's value is, and it does equal what's contained in the DIV. For the moment I was just trying to change it to "test" until I get it working, but it doesn't work. Can anbydoy help me out at all?
 
Try something like this:

Code:
ver iH = myArray[i].innerHTML.replace("/" + searchString + "/g", "<strong>" + searchString + "</strong>");
myArray[i].style.display = 'block';

Sorry, I'm new to RegEx's, but I think that should get you started.

*cLFlaVA
----------------------------
[tt]tastes great, less filling.[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
>>cLFlaVA

i wouldnt do that, that would not only replace normal text but also text within HTML tags.

i have written a script for this, you may wanna modify it:
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[URL unfurl="true"]http://www.w3.org/TR/html4/loose.dtd">[/URL]
<html>
<head>
<title>How To Use This Handbook</title>
<link rel="stylesheet" type="text/css" href="../style.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
<!--
.hardcopy {color: #CC0000}
-->
</style>

<title>Searchable Table</title>

<script type="text/javascript">
<!--

function searchTable(txt)
{

	if(txt.match(/^$/))
	{
		alert("Please enter a search string.")
		return false
	}

	//Replace special characters:
	txt=txt.replace(/\./g,"\\.")
	txt=txt.replace(/\+/g,"\\+")
	txt=txt.replace(/\*/g,"\\*")
	txt=txt.replace(/\?/g,"\\?")

	TheCount=0

	var re = new RegExp("("+txt+")","gi")
	var TheTbl= document.getElementById('tbl_to_search');
	TheTBody=TheTbl.childNodes[0]
	for(i=0;i<TheTBody.childNodes.length;i++)
	{
		TheTr=TheTBody.childNodes[i]
		for(j=0;j<TheTr.childNodes.length;j++)
		{
			TheTd=TheTr.childNodes[j]
			TheHtml=TheTd.innerHTML.replace(/<[^\s].*?>/gi,"")
			if(TheHtml.match(re))
			{
				TheHtml=TheTd.innerHTML
				TheHtml=TheHtml.replace(/\n/g,"")
				TheHtml=TheHtml.replace(/\r/g,"")
				
				TheHtml=TheHtml.replace(/<font color='?red'? DONEBYSEARCH><b>([^<]+)<\/b><\/font>/gi,"$1")
				

				

				TheHtml1=TheHtml.replace(re,"###$1###")
				
				while(TheHtml1.match(/<[^>]*###([^#]+)###[^>]*>/))
				{
					TheHtml1=TheHtml1.replace(/<([^#]*)###([^#]+)###([^>]*)>/g,"<$1$2$3>")
				}
			
				if(TheHtml1.match(/###([^#]+)###/))
					TheCount+=TheHtml1.match(/###([^#]+)###/g).length

				TheHtml1=TheHtml1.replace(/###([^#]+)###/g,"<font color='red' DONEBYSEARCH><b>$1</b></font>")
				TheTd.innerHTML=TheHtml1
			}
			else
			{
				TheHtml=TheTd.innerHTML
				TheHtml=TheHtml.replace(/\n/g,"")
				TheHtml=TheHtml.replace(/\r/g,"")
				TheHtml=TheHtml.replace(/<font color='?red'? DONEBYSEARCH><b>([^<]+)<\/b><\/font>/gi,"$1")
				TheTd.innerHTML=TheHtml
			}
		}
	}
	if(TheCount==0)
	{
		alert("No results found were found for the word '"+txt+"'.")
	}
	else
	{
		PluralSingluar="es"
		if(TheCount==1)
			PluralSingluar=""

		TheStr="&nbsp;&nbsp;&nbsp;<b>"+TheCount+" match"+PluralSingluar+" found.</b>"
		document.getElementById("MatchCountDiv").innerHTML=TheStr
	}
}        
// -->
</script>

</head>

<body leftmargin="20" topmargin="0" marginwidth="0" marginheight="0">
<p><strong>Vendor Hyperlinks</strong></p>
<p><strong></strong></p>
<p><strong>Scope: </strong></p>
<p>Metro Library Links. </p>
<p><strong>Purpose: </strong></p>
<p>To document which parts are purchased from which vendors, and reference their corresponding website address. </p>
<p><strong>Introduction: </strong></p>
<p>The Metro Library is basically a catalog of parts organized by manufacturer. These pages are an effort to reduce paperwork and keep information current. Items not available for internet access will be noted &quot;<span class="hardcopy">SEE HARDCOPY REFERENCE</span>.&quot; </p>
<p><strong>Description:</strong></p>

<form onsubmit="return false">
  <input type="text" name="srch" value="grip" onkeydown="event.keyCode==13?searchTable(this.form.elements ['srch'].value):''">
  <input type="button" value="Search!" onclick="searchTable(this.form.elements ['srch'].value);">
  <br>
  <div id="MatchCountDiv">&nbsp;</div>
</form>
<br>
<table width="780" border="1" id="tbl_to_search">
  <tr>
    <th width="360" scope="col">Vendor Reference</th>
    <th scope="col">Product</th>
  </tr>
  <tr>
    <td><a href = "[URL unfurl="true"]http://www.agi-automation.com/"[/URL] class="MenuItem">AGI Automation 
      Compo nents </a></td>
    <td><a href = "[URL unfurl="true"]http://www.agi-automation.com/Pneumatic-grippers.htm"[/URL] class="MenuItem"> Grippers</a>, <a href = "[URL unfurl="true"]http://www.agi-automation.com/rotary-actuators.htm"[/URL] class="MenuItem">Rotary Actuators</a>, <a href = "[URL unfurl="true"]http://www.agi-automation.com/linear-actuator.htm"[/URL] class="MenuItem">Powered Slides</a>, <a href = "[URL unfurl="true"]http://www.agi-automation.com/miniature-linear-actuator.htm"[/URL] class="MenuItem">Mini Power Slides</a>, <a href = "[URL unfurl="true"]http://www.agi-automation.com/Linear-escapements.htm"[/URL] class="MenuItem">Feed Escapement</a>, <a href = "[URL unfurl="true"]http://www.agi-automation.com/EOAT-tool-changer.htm"[/URL] class="MenuItem">Hand Exchange</a> and <a href = "[URL unfurl="true"]http://www.agi-automation.com/eoat-load-limiter.htm"[/URL] class="MenuItem">Load Limiters</a>.</td>
  </tr>
  <tr>
    <td><a href = "[URL unfurl="true"]http://www.alcoa.com/gcfp/en/product.asp?cat_id=969&prod_id=1711"[/URL] class="MenuItem">ALCOA UltrAlloy 6020 </a></td>
    <td>Lead Free Aluminum Product.</td>
  </tr>
</table>
<p>&nbsp;</p>
</body>
</html>

try it out...

Known is handfull, Unknown is worldfull
 
Sorry, I left a part out. This works:

Code:
function doMySearch()
{
var searchObj2 = document.forms['search'].elements['searchString'].value;
var searchString = new RegExp(searchObj2,"gi");

var myArray = document.getElementsByTagName("div");
for(var i = 0; i < myArray.length; i++)
{
    var searchText = myArray[i].innerHTML;
    var searchResult = searchText.match(searchString);
if(searchResult)
    {
        var str = myArray[i].innerHTML.replace(searchString , "<strong>" + searchObj2 + "</strong>");
        myArray[i].innerHTML = str;
        myArray[i].style.display='block';
    } else {
        myArray[i].style.display='none';
  }
 }
}

*cLFlaVA
----------------------------
[tt]tastes great, less filling.[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
can i have the html file code on which this was tested???

Known is handfull, Unknown is worldfull
 
same here...

Known is handfull, Unknown is worldfull
 
Thanks to you both for your replies. vbkris - yours works, but I'm really new to RegExp so would you mind explaining the RegExp parts of your code to me? Also, I can't seem to get the .replace function to work, only .match in RegExp - why is this. Isn't the syntax, myText.replace(text to search for, text to replace)?

Thanks in advance
 
hi,

give me sometime, i will give you a detailed explanation...

Known is handfull, Unknown is worldfull
 
section wise explanation:

Installment 1
if(txt.match(/^$/))
this checks if the string is empty, u could always use txt.length==0 to check that but i used RegEx. the stmt means that if a string starts and ends (^,$) then it will decide that its empty...


//Replace special characters:
txt=txt.replace(/\./g,"\\.")
txt=txt.replace(/\+/g,"\\+")
txt=txt.replace(/\*/g,"\\*")
txt=txt.replace(/\?/g,"\\?")
., +, *, ? are special RegEx characters that if entered by the user should be commented.

var re = new RegExp("("+txt+")","gi")
the above string creates a regex to match the text...

next installment soon... ;)

Known is handfull, Unknown is worldfull
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top