I’m trying to create a function that takes in a string and outputs a value of true if any of the ‘a’s in the string are exactly 3 places from the ‘b’s in the same string. If the ‘a’s and ‘b’s are not exactly 3 places from one another than return false.
Examples
Input: "after badly"
Output: false
Input: "Laura sobs"
Output: true
This is what I have so far but it doesn’t seem to be working. If anyone could take a look and show me where I’ve gone wrong that would be awesome.
function string(str) {
for (i = 0; i < str.length; i++) {
if(str[i] === 'a' && str[i+3] === 'b'){
return true;
}
}
return false;
}
console.log(string('lane borrowed'))
>Solution :
You will only get the third element based on your code. Since i+3 get the third element from the i which should be two space apart not three space.
function string(str) {
for (i = 0; i < str.length; i++) {
if(str[i] === 'a' && str[i+4] === 'b'){
return true;
}
}
return false;
}
console.log(string('lane borrowed'))