How to use trim(), split(), and join() Methods In Javascript
First, we will use the trim() method to remove extra space from the starting and ending, then use the split() method to split the string from spaces and then use the join() method to join the split string using a single space.
Example: This example shows the implementation of the above-explained approach.
// String containing multiple spaces
let str = " Welcome to Geeks for Geeks ";
// Replace multiple spaces with single space
let newStr = str.trim().split(/[\s,\t,\n]+/).join(' ');
// Display the result
console.log(newStr);
Output
Welcome to Geeks for Geeks
How to replace multiple spaces with single space in JavaScript ?
In this article, we will see how to replace multiple spaces with a single space in JavaScript. We will have a string having multiple spaces and we need to remove those extra spaces.
There are two methods to replace multiple spaces with a single space in JavaScript:
Table of Content
- Method 1: Using replace() Method
- Method 2: Using trim(), split(), and join() Methods
- Method 3: Using a Regular Expression with replace() Method and Trim()