Reputation: 21
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");
Upvotes: 2
Views: 34810
Reputation: 2075
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);
Upvotes: 5
Reputation: 68393
substring returns the part of the string between the start and end indexes, or to the end of the string.
If you want to compare only first character, use charAt
function compare(wordOne, wordTwo) {
return wordOne.charAt(0) === wordTwo.charAt(0);
}
compare("house", "hell");
Or you can pass the index as the parameter
function compare(wordOne, wordTwo, index) {
return wordOne.charAt(index) === wordTwo.charAt(index);
}
compare("house", "hell", 0);
Upvotes: 2
Reputation: 4635
To explain why your current code doesn't work, you need to pass a second parameter to .substring
as the to
value. String.substring(0)
just returns the whole string after the 0th character, so the entire word. Fixed example;
function compare(wordOne, wordTwo) {
if (wordOne.substring(0, 1) === wordTwo.substring(0, 1)) {
return true;
}
else
{
return false;
}
}
compare("house", "hell");
You could also just use wordOne[0] === wordTwo[0]
Upvotes: 4