Domino Code Fragment

Code Name*
Search and Replace
Date*
01/31/1999
Source (or email address if you prefer)*
Jamie Magee
IP address:.3.129.19.251
Description*
Searches for a term in a target string and replaces it with another string.
Type*
JavaScript
Categories*
List Processing/Sorting, (Misc)
Implementation:
None (plug and play)
Required Client:
JavaScript 1.0
Server:
Limitations:
Comments:
Files/Graphics attachments (if applicable): Code:
function replace(target, oldTerm, newTerm, caseSens, wordOnly) {
// SEARCH FOR A TERM IN A TARGET STRING AND REPLACE IT
//
// replace(targetstring,oldTerm,newTerm,caseSensitive,WordOrSubstring)
//
// where CaseSensitive is a boolean value and wordOrSubstring is a boolean
// value and true means whole words, false means substrings
//
       var work = target;
       var ind = 0;
       var next = 0;


        if (!caseSens) {
               oldTerm = oldTerm.toLowerCase();
               work = target.toLowerCase();
       }


        while ((ind = work.indexOf(oldTerm,next)) >= 0) {
               if (wordOnly) {
                       var before = ind - 1;
                       var after = ind + oldTerm.length;
                       if (!(space(work.charAt(before)) && space(work.charAt(after)))) {
                               next = ind + oldTerm.length;
                               continue;
                       }
               }
               target = target.substring (0,ind) + newTerm + target.substring(ind+oldTerm.length,target.length);
               work = work.substring(0,ind) + newTerm + work.substring(ind+oldTerm.length,work.length);
               next = ind + newTerm.length;
               if (next >= work.length) { break; }
       }
       return target;
}


//CHECK IF A CHARACTER IS A WORD BREAK AND RETURN BOOLEAN VALUE
//
function space (check) {
       
       var space = " .,/<>?!`';:@#$%^&*()=-|[]{}" + '"' + "\\\n\t";


        for (var i = 0; i < space.length; i++)
               if (check == space.charAt(i)) { return true; }


        if (check == "") { return true; }
       if (check == null) { return true; }


        return false;
}