Home

Remove extra spaces in a string in JavaScript

If you want to remove any character from a string, you can use replace method, but if you only want to remove extra spaces that were mistakenly typed and to keep just a single white space between any two words of a sentence, you need to use a regular expression.

const message =
  "This  is a  long    message that's   carelessly typed with  many   spaces.       ";

message.replace(/\s/gi, '');
// Output → "Thisisalongmessagethat'scarelesslytypedwithmanyspaces."

message.replace(/\s+/gi, ' ');
// Output → "This is a long message that's carelessly typed with many spaces. "

Note: There is a space at the end. You can remove it by using the trim method.

message.replace(/\s+/gi, ' ').trim();
// Output → "This is a long message that's carelessly typed with many spaces."

If you don't care about the special characters, you can use message.replace(/\W/gi , ' ').trim(). But I won't recommend it.



Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments