Introduction
In this lab, we will explore how to check if a given string contains any whitespace characters using regular expressions in JavaScript. The lab will provide a step-by-step guide on how to use the RegExp.prototype.test() method to check if a string contains any whitespace characters. By the end of this lab, you will have a better understanding of how to check for whitespace characters in JavaScript strings.
Checking for Whitespace in a String
To check if a string contains whitespace characters, follow the steps below:
Open the Terminal/SSH and type
nodeto start practicing coding.Use
RegExp.prototype.test()with an appropriate regular expression to check if the given string contains any whitespace characters.Here's an example code snippet:
const containsWhitespace = (str) => /\s/.test(str);To test the function, call
containsWhitespacewith a string as an argument. It will returntrueif the string contains whitespace characters, otherwisefalse.containsWhitespace("lorem"); // false containsWhitespace("lorem ipsum"); // true
Summary
Congratulations! You have completed the Check if String Contains Whitespace lab. You can practice more labs in LabEx to improve your skills.