w3resource

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 will return 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:

JavaScript Fundamental: Return true if the string is y/yes other wise false

Flowchart:

flowchart: Return true if the string is y/yes other wise false

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.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]