Testing distance between characters in a string
I would recommend using a regular expression.  Regex is designed for solving pattern matching and string manipulation problems. Although it can look esoteric and terse it is well worth the effort to learn since it is very powerful and fairly ubiquitous.  It is very likely your programming language/shell/editor of choice supports a flavor of regex.

var str = prompt("Please enter a string: ");

function test(str){ 
  return /a\w{3}b/.test(str) || /b\w{3}a/.test(str); 
}

console.log(test(str));