[Javascript] How to replace multiple whitespaces with single whitespace?


I want to replace all multiple whitespaces with a single whitespace, How to do that in Javascript?

1 Answer

3 years ago by

Use the regex as /\s+/g which represents multiple whitespace and replace it with a single whitespace using replace() methos as shown below:

let str = "This                 is a              test        message";

console.log(str.replace(/\s+/g, " "));

Run here https://onecompiler.com/javascript/3xnrmcvyt

3 years ago by Meera