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:
We will use the replace() method to replace multiple spaces with a single space in JavaScript. First, we use the regular expression /\s+/g to match one or more spaces globally in the string and then replace it with the ‘ ‘ value.
Example: This example shows the implementation of the above-explained approach.
Javascript
let str = " Welcome to Geeks for Geeks " ;
let newStr = str.replace(/\s+/g, ' ' );
console.log(newStr);
|
Output
Welcome to Geeks for Geeks
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.
Javascript
let str = " Welcome to Geeks for Geeks " ;
let newStr = str.trim().split(/[\s,\t,\n]+/).join( ' ' );
console.log(newStr);
|
Output
Welcome to Geeks for Geeks
Last Updated :
07 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...