String Manipulation with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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.


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-28590{{"String Manipulation with JavaScript"}} javascript/data_types -.-> lab-28590{{"String Manipulation with JavaScript"}} javascript/arith_ops -.-> lab-28590{{"String Manipulation with JavaScript"}} javascript/comp_ops -.-> lab-28590{{"String Manipulation with JavaScript"}} end

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.