JavaScript: Return true if the string is y/yes other wise false
JavaScript fundamental (ES6 Syntax): Exercise-26 with Solution
Write a JavaScript program that returns true if the string is y/yes or false if the string is n/no.
- Use RegExp.prototype.test() to check if the string evaluates to y/yes or n/no.
- Omit the second argument, def to set the default answer as no.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const yes_No = (val, def = false) =>
/^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
console.log(yes_No('Y'));
console.log(yes_No('yes'));
console.log(yes_No('No'));
console.log(yes_No('Foo', true));
Note: Omit the second argument, def to set the default answer as no.
Sample Output:
true true false true
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-26 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create a new array out of the two supplied by creating each possible pair from the arrays.
Next: Write a JavaScript program to find every element that exists in any of the two given arrays once, using a provided comparator function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join