logo

replace (javascript)

JavaScript: The Definitive Guide

I wrote the replace function to look for string pattern and replace it with another string pattern. The function allows for multiple occurances of a search string - replacing its with another string. The & symbol gave me alittle trouble, so a special case was developed to deal with it.


function replace(stPhrase,stPattern,stInsert)
{
	var stBuffer;
	stArray=stPhrase.split(stPattern);
	stBuffer="";
	for(var i=0; i<stArray.length; i++)
	{	
		if(i<stArray.length-1)
		{
			if((stInsert=='lt;')||(stInsert=='gt;'))
			{
			stBuffer+=stArray[i]+"&"+stInsert;
			}
			else
			{
			stBuffer+=stArray[i]+stInsert;
			}
		}
		else
		{
			stBuffer+=stArray[i];
		}
	}
	return stBuffer;
}
s