Free, tested & ready to use examples!
AnyExample.com
 
Web anyexample.com
 

JS string compare example

abstract 
JavaScript string comparing is a very common operation for most of JS developers. Basically it's a check if one string equals another.
But there are some tricky "issues" in JavaScript when doing comparison. I will try to describe some of them and give few advices to deal with them.
compatible 
  • All modern web-browsers.
  • Let's start with a simple code snippet in JS:

    var s = 'string';
    
    if(s == 'string') {
        alert(true);
    } else {
        alert(false);
    }
    

    Yes, it puts an alert 'true' on the screen. Pretty straightforward so far. And another example:

    var s = '123';
    
    if(s == 123) {
        alert(true);
    } else {
        alert(false);
    }
    

    This code shows 'true' too... don't you think that's strange? Comparing a number to a string gives you true. Anyway, another example:

    var s = '';
    
    if(s === '123') {
        alert(true);
    } else {
        alert(false);
    }
    

    Finally! We got 'false' alert this time, but have noted this difference in last two example?
    In the second example, usual '==' operator was used to test two objects if they're equal. Now we're using '===' operator, it ensures that compared objects are the same in a matter of type also. Using simple comparison operator usually uses .toString() operator for a non-string types. That's why 123=='123' in a JavaScript world.

    There is another interesting stuff with expressions inside the 'if' statement. For example, if you wan't to test passed parameter inside a function, you should be very careful:

    function testParam(param) {
        if(param) {
            alert(true);
        } else {
            alert(false);
        }
    }
    
    testParam('test');//true
    testParam(null);//false
    testParam();//false
    testParam('');//this also gives you 'false', same like if null or undefined param was passed
    

    Good, that was simple. Comparing one string to another is always easy, but what if you need to test if some string has a substring that you're searching?
    There are two things that can help you in that case - String.indexOf() method and RegExp objects for matching strings.

    alert('Hello JavaScript world!'.indexOf('world'), 5);//start search from the 6th symbol
    alert('Hello JavaScript world!'.indexOf('foobar'));
    

    This example will give you '17' and then '-1' as a result. indexOf() returns an index of char in the string where match was found. You can provide optional param to start search only from that specific position in the string.
    Ok, that was simple too :)

    var regex = new RegExp('[0-9]+');
    alert('abc433qwe234'.match(regex));//output is '433'
    
    var regex2 = new RegExp('[0-9]+', 'ig');
    alert('abc433abc123'.match(regex2));//output is an array: '433, 123'
    

    In this example we're searching for a number as a substring in 'abc433' using the RexExp object. '[0-9]' means we're searching for digits and '+' means we wan't to all digits following the first that matched.
    Second regex2 test gives us an array of all grouped digits found in the string. Note that we're passing optional param 'ig'. 'i' here means case insensitive search, 'g' is for global search - look up all matches and give output as an array.
    Full description of RegExp class params you can look up here.



    tested 
  • Chrome 5, Mac OS X 10.6
  •  


     
    © AnyExample 2010-2013
    License | Privacy | Contact