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, "");

For example,

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

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.

Other JavaScript Tutorials you may like