Check Yes/No String

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28699{{"`Check Yes/No String`"}} javascript/data_types -.-> lab-28699{{"`Check Yes/No String`"}} javascript/arith_ops -.-> lab-28699{{"`Check Yes/No String`"}} javascript/comp_ops -.-> lab-28699{{"`Check Yes/No String`"}} end

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.

Other JavaScript Tutorials you may like