You can use the replace() method to replace multiple spaces with a single space in a string in JavaScript. One way to do this is to use a regular expression with the ‘/\s+/g’ pattern, which matches one or more consecutive whitespace characters (spaces, tabs, and line breaks). Here’s an example:

let str = "Hello, world!";
let newStr = str.replace(/\s+/g, " ");
console.log(newStr); // "Hello, world! "

Alternatively, you can use split() method to split the string into an array of words, then use join() method to join them back together with a single space. Here’s an example:

let str = "Hello, world!";
let newStr = str.split(" ").filter(Boolean).join(" ");
console.log(newStr); // "Hello, world!"

This splits the string into an array of words, filter out the empty string element, then joins them back together with a single space.

It is important to note that the replace() method replaces all occurrences of the specified pattern, while split() and join() method will only remove the extra spaces between words.

Also Read:

Categorized in: