@ReplaceSubString in JavaScript

Mindwatering Incorporated

Author: Tripp W Black

Created: 06/07/2002 at 07:29 PM

 

Category:
Notes Developer Tips
JavaScript

The script below's compare is case sensitive by default.

*Offered freely by Darren J Semotiuk, Collaborative Learning Network Inc.,
http:////www.co-learn.net/ Just keep this comment line intact. Thanks! *

CODE

function replacestring(str_normal,str_find,str_replace,int_case_insensitive)
{
if (arguments.length<3 || str_find=="" || str_normal=="" ||
typeof("".split)!="function")
return(str_normal);

//no parm means default, "case SENSITIVE"...
if(!(int_case_insensitive))
return(str_normal.split(str_find)).join(str_replace);

str_find=str_find.toLowerCase();

var rv="";
var ix=str_normal.toLowerCase().indexOf(str_find);
while(ix>-1)
{
rv+=str_normal.substring(0,ix)+str_replace;
str_normal=str_normal.substring(ix+str_find.length);
ix=str_normal.toLowerCase().indexOf(str_find);
};
return(rv+str_normal);
};//end function replacestring



OR
better yet, a one-liner you paste in ANYWHERE...


function rs(sd,sf,sr,ic){if(arguments.length<3||sf==""||sd==""||typeof("".split)
!="function")return(sd); /*no parm means default, "case
SENSITIVE"...*/if(!(ic))return(sd.split(sf)).join(sr);
sf=sf.toLowerCase();var rv="";var
ix=sd.toLowerCase().indexOf(sf);while(ix>-1)
{rv+=sd.substring(0,ix)+sr;sd=sd.substring(ix+sf.length);ix=sd.to
LowerCase
().indexOf(sf);};return(rv+sd);};


previous page