In this article, we will see how to replace multiple spaces with a single space in JavaScript.
There are two methods to replace multiple spaces with a single space in JavaScript.
We will use 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:
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 trim() method to remove extra space from 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:
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Jul, 2023
Like Article
Save Article