display | more...
This JavaScript function will try to locate a passed substring within a passed string. If it is found it will return 'TRUE' otherwise, 'FALSE'.

function findString(tstring,text) {
    // Replaces text with by in string
    var strLength = tstring.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)){
        return false;
    }
    var i = tstring.indexOf(text);
    if (i == -1) {
        return false;
    }
    else{
        return true;
    } 
}

Here's a more graceful and convenient way to do it, which also shows us a little bit about why JavaScript classes are such charming little creatures. What's charming about them is the fact that you can alter a class after it's been defined -- not merely an instance of the class, but the class itself.

What we do here is simple, yet somewhat strange and wonderful to a C++ programmer (which I am): We add a new member function to the built-in String class. It's not terribly useful, except when you grow weary of comparing the return value of String.indexOf() to -1 and you want something that returns a boolean instead. We prefer a member function to a non-member function because it makes for consistency in use. It's fun, too.

The dark side to this kind of thing is that most normal programmers will expect that any member of a built-in class is going to be standard. If such a programmer borrows a snippet of your code, hilarity may ensue. Somebody who just reads your code may also walk away with some strange notions.

    //  Add new member function to class.

    String.prototype.contains = String_contains;


    //  Define the member function. It doesn't matter 
    //  in what order you do these two things.

    function String_contains( s ) {
        //  Refer to this explicitly
        return s.length && ( this.indexOf( s ) != -1 );
    }


    //  Use it like this:
    var s = 'foo bar baz';
    alert ( s.contains( 'foo' ) ? 'foo!' : 'No foo for you, Peggy Sue!' );

Note that the code is a bit simpler than that above: We don't waste time looking at the length of this, because the only string that will ever be found within an empty string is another empty string. That case gets covered anyway, when we look at the length of the argument s. It's probably not a monstrously big efficiency issue, but redundant code makes Jesus cry. We also don't define any local variables, since we only look at any given value once. We don't bother with return true and return false because we're returning the value of a boolean expression, which is already true or false.


I tested this rather casually. Bug reports, flames, allegations of financial impropriety, etc. are more than welcome.

Log in or register to write something here or to contact authors.