Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q229 How can you filter multiple words in an array and replace them with other words?

You are here: irt.org | FAQ | JavaScript | Text | Q229 [ previous next ]

The following uses Regular Expressions which will work on either Netscape Navigator 4 or Internet Explorer 4:

<HTML>
<HEAD>
<SCRIPT language="JavaScript"><!--
a = new Array("BAD Word", "Awful word", "Nasty Word", "good", "TERRIBLE Word", "good");

b = new Array();
b[0] = /terrible/gi;
b[1] = /bad/gi;
b[2] = /awful/gi;
b[3] = /nasty/gi;

c = new Array("Nice","Sweet","Innocent","Lovely");

//--></SCRIPT>
</HEAD>

<BODY>

<P>Here is the old array, with bad words in it:
<P>

<SCRIPT language="JavaScript"><!--
for (var i = 0 ; i < a.length ; i ++) {
    document.write(a[i] + '<BR>');
}
//--></SCRIPT>

<P>Now here is the array with the bad words you want to filter out replaced with good ones:
<P>

<SCRIPT language="JavaScript1.2"><!--
for(var i = 0 ; i < a.length ; i ++ ) {
    for (var j = 0 ; j < b.length ; j ++) {
        if (a[i].search(b[j]) != -1) {
            a[i] = a[i].replace(b[j],c[j]);
        }
   }
}

for(var i = 0 ; i < a.length ; i ++ ) {
    document.write(a[i] + '<BR>');
}
//--></SCRIPT>

</BODY>
</HTML>

©2018 Martin Webb