Compact Whitespaces in JavaScript Strings

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to compact whitespaces in a string using JavaScript. We will utilize the String.prototype.replace() method and a regular expression to replace all occurrences of two or more whitespace characters with a single space. This will help us to effectively format and clean up text data in our web applications.


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-28207{{"`Compact Whitespaces in JavaScript Strings`"}} javascript/data_types -.-> lab-28207{{"`Compact Whitespaces in JavaScript Strings`"}} javascript/arith_ops -.-> lab-28207{{"`Compact Whitespaces in JavaScript Strings`"}} javascript/comp_ops -.-> lab-28207{{"`Compact Whitespaces in JavaScript Strings`"}} end

Function to Compact Whitespaces in a String

To compact whitespaces in a string, use the compactWhitespace() function.

  • It uses String.prototype.replace() with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.
  • The function takes a string as an argument and returns the compacted string.
const compactWhitespace = (str) => str.replace(/\s{2,}/g, " ");

Example usage:

compactWhitespace("Lorem    Ipsum"); // 'Lorem Ipsum'
compactWhitespace("Lorem \n Ipsum"); // 'Lorem Ipsum'

Summary

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

Other JavaScript Tutorials you may like