Check Yes/No String

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript code snippet designed to check if a string input represents a 'yes' or 'no' answer. The yesNo function uses regular expressions to test if the input matches 'y' or 'yes' for a true response, 'n' or 'no' for a false response, or a default value if none is provided. You will have the opportunity to test this function with different inputs and defaults, and gain a better understanding of how regular expressions can be used in JavaScript.

Function to Check Yes/No String

To check if a string is a 'yes' or 'no' answer, use the following function in the Terminal/SSH by typing node:

const yesNo = (val, def = false) =>
  /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
  • The function returns true if the string is 'y'/'yes' and false if the string is 'n'/'no'.
  • To set a default answer, omit the second argument def. By default, the function will return false.
  • The function uses RegExp.prototype.test() to check if the string matches 'y'/'yes' or 'n'/'no'.

Example usage:

yesNo("Y"); // true
yesNo("yes"); // true
yesNo("No"); // false
yesNo("Foo", true); // true

Summary

Congratulations! You have completed the Check Yes/No String lab. You can practice more labs in LabEx to improve your skills.