w3resource

JavaScript: Check whether the characters a and b are separated by exactly 3 places anywhere in a given string

JavaScript Basic: Exercise-53 with Solution

Write a JavaScript program to check whether the characters a and b are separated by exactly 3 places anywhere (at least once) in a given string.

This JavaScript program scans a given string to determine if the characters 'a' and 'b' are separated by exactly three characters. It iterates through the string, checking the positions of 'a' and 'b' to ensure they meet the specified separation condition.

Visual Presentation:

JavaScript: Check whether the characters a and b are separated by exactly 3 places anywhere in a given string

Sample Solution:

JavaScript Code:

// Define a function named ab_Check with parameter str
function ab_Check(str) {
    // Use regular expressions to check if the pattern 'a...b' or 'b...a' exists in the given string
    // The test() method returns true if the pattern is found, otherwise, it returns false
    return (/a...b/).test(str) || (/b...a/).test(str);
}

// Log the result of calling ab_Check with the given strings to the console
console.log(ab_Check("Chainsbreak"));
console.log(ab_Check("pane borrowed"));
console.log(ab_Check("abCheck")); 

Output:

true
true
false

Live Demo:

See the Pen JavaScript - Check whether the characters a and b are separated by exactly 3 places - basic-ex-53 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Check whether the characters a and b are separated by exactly 3 places anywhere in a given string

ES6 Version:

 // Define a function named ab_Check with parameter str
const ab_Check = (str) => {
    // Use regular expressions to test if the string contains either "a...b" or "b...a" patterns
    return (/a...b/).test(str) || (/b...a/).test(str);
};

// Log the result of calling ab_Check with the given strings to the console
console.log(ab_Check("Chainsbreak"));
console.log(ab_Check("pane borrowed"));
console.log(ab_Check("abCheck"));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to convert the letters of a given string in alphabetical order.
Next: JavaScript program to count the number of vowels of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-basic-exercise-53.php