I need to create a function, lettersAfter()
, that accepts three arguments:
haystack
: The string to be searchedneedle
: A character to search for.limit
: The number of letters after the character to return
lettersAfter()
should return the letters following the first found occurrence of the search character. The letters returned should be limited to the number of the third argument.
For example:
lettersAfter('hello', 'e', 2); // => 'll'
lettersAfter('hello', 'h', 1); // => 'e'
lettersAfter('indefatigable', 'a', 4); // => 'tiga'
This is my code:
function lettersAfter(haystack, needle, limit) {
let letters = ''
for (i = 0; i < haystack.length; i++) {
if (needle === haystack[i]) {
for (j = 0; j < limit; j++) {
letters += haystack[i + j + 1];
}
}
}
return letters;
}
console.log(lettersAfter('Bobthebuilder', 'b', 5));
According to the prompt, the code should return 'thebu'
, but it ends up returning 'thebuuilde'
. Any advice?
2
Answers
The issue is that after the character is found the first time, the loop keeps going and will add more to
letters
if the same character is found a second time. To fix this,break
out of the loop after you find it the first time:However, in the real world, it’s better to just use the built-in functions
.indexOf()
and.substring()
. To replicate returning an empty string if there is no match, just check if.indexOf()
returns-1
:Another option is to use
indexOf
to find your ‘needle’ and use the found index (if there is one) and the limit to determine asubstring
to return. In the code below, indexOf is used to find the index and 1 is added to this index because we want the letters afterneedle
. Then we check to see iffirstIndex > 0
because indexOf returns -1 if no index was found, but since we added 1 this would now be 0. If the condition is true, take a substring from firstIndex and check if the remaining length is less than the limit. I added a return statement for the condition being false to indicate that no index was found.NOTE: If the
needle
can be more than 1 letter/character, you would need to change+1
to+needle.length
when assigning a value tofirstIndex
.