Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I return a value of true if the letters 'a' and 'b' are exactly 3 places apart?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading