Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Text | Q229 [ previous next ]

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

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.