javascriptstringfunctionsubstring

How to compare only first character of 2 strings (javascript)?


Trying to write a javascript function for comparing only first character of 2 strings but can't make it work. Here is the code.

function compare(wordOne, wordTwo) {
    if (wordOne.substring(0) === wordTwo.substring(0))
    {
        return true;
    } else {
        return false;
    }
}
compare("house", "hell");

Solution

  • Assuming you want to compare the first letter of the two strings, you can use the following code

    function compare(wordOne, wordTwo) {
        return wordOne[0] === wordTwo[0];
    }
    compare("house", "hell");
    

    This condenses the if/else condition, as you are just interested in whether the first letters are equal - not in how different they are. You can also use str.toUpperCase() (or) str.toLowerCase() in order to make the comparison case insensitive.

    As per @Josh Katofsky's suggestion, you can of course make this function more versatile by - for instance - adding a third parameter that tests the n-th letter:

    function compare(wordOne, wordTwo, index) {
        return wordOne[index] === wordTwo[index];
    }
    compare("house", "hell", 0);