String Manipulation with JavaScript

Beginner

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

Introduction

In this lab, we will explore the concept of string manipulation in JavaScript. Specifically, we will focus on removing whitespaces from strings using regular expressions. Through a series of exercises and examples, we will gain a deeper understanding of how to use the String.prototype.replace() method to remove whitespace characters and create cleaner, more manageable strings.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Function to Remove Whitespaces

To remove whitespaces from a string, use the following function.

  • Use String.prototype.replace() with a regular expression to replace all occurrences of whitespace characters with an empty string.
const removeWhitespace = (str) => str.replace(/\s+/g, "");

Regular Expression Explained

  • /\s+/g breaks down as:
    • \s: Matches any whitespace character (spaces, tabs, line breaks)
    • +: Matches one or more occurrences of the previous character
    • /g: Global flag - matches all occurrences in the string, not just the first one

Quick Regex Reference

Common whitespace patterns:

  • \s - matches any whitespace (space, tab, newline)
  • \t - matches tab characters
  • \n - matches newline characters
  • \r - matches carriage returns
  • `` (space) - matches only space characters

For example,

removeWhitespace("Lorem ipsum.\n Dolor sit amet. ");
// 'Loremipsum.Dolorsitamet.'

// More examples:
removeWhitespace("Hello    World"); // "HelloWorld"
removeWhitespace("Tab\there\nNew line"); // "TabhereNewline"

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Remove Whitespaces lab. You can practice more labs in LabEx to improve your skills.