home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Previous Section Next Section

1.5 Testing String Containment Without Regular Expressions

NN 2, IE 3

1.5.1 Problem

You want to know if one string contains another, without using regular expressions.

1.5.2 Solution

Use the JavaScript indexOf( ) string method on the longer string section, passing the shorter string as an argument. If the shorter string is inside the larger string, the method returns a zero-based index integer of the start position of the smaller string within the larger string. If the shorter string is not in the larger string, the method returns -1.

For logic that needs to branch if the smaller string is not contained by the larger string, use the following construction:

if (largeString.indexOf(shortString) =  = -1) {
    // process due to missing shortString
}

For logic that needs to branch if the smaller string is contained somewhere within the larger string, use the following construction:

if (largeString.indexOf(shortString) != -1) {
    // process due to found shortString
}

In either case, you are not interested in the precise position of the short string but simply whether it is anywhere within the large string.

1.5.3 Discussion

You may also find the integer returned by the indexOf( ) method to be useful in a variety of situations. For example, an event handler function that gets invoked by all kinds of elements in the event-propagation (bubbling) chain wants to process events that come only from elements whose IDs begin with a particular sequence of characters. This is an excellent spot to look for the returned value of zero, pointing to the start of the larger string:

function handleClick(evt) {
    var evt = (evt) ? evt : ((window.event) ? window.event : null);
    if (evt) {
        var elem = (evt.target) ? evt.target : ((evt.srcElement) ? 
            evt.srcElement : null);
        if (elem && elem.id.indexOf("menuImg") =  = 0) {
            // process events from elements whose IDs begin with "menuImg"
        }
    }
}

Be aware that if the larger string contains multiple instances of the shorter string, the indexOf( ) method returns a pointer only to the first instance. If you're looking to count the number of instances, you can take advantage of the indexOf( ) method's optional second parameter, which specifies the starting position for the search. A compact repeat loop can count up the instances quickly:

function countInstances(mainStr, srchStr) {
    var count = 0;
    var offset = 0;
    do {
        offset = mainStr.indexOf(srchStr, offset);
        count += (offset != -1) ? 1 : 0;
    } while (offset++ != -1)
    return count
}

Counting instances is much easier, however, using regular expressions (see Recipe 1.6).

1.5.4 See Also

Recipe 1.6 for using regular expressions to test string containment.

    Previous Section Next Section