[Home] > Snippets  > Languages  > JavaScript  > Strings  >  Replace multiple spaces with a single space

Replace multiple spaces with a single space

JavaScript

// Replace spaces, tabs and new line characters
const replaceSpaces = (str) => str.replace(/\s\s+/g, ' ')

// Only replace spaces
const replaceOnlySpaces = (str) => str.replace(/ +/g, ' ')

TypeScript

const replaceSpaces = (str: string): string => str.replace(/\s\s+/g, ' ')

const replaceOnlySpaces = (str: string): string => str.replace(/ +/g, ' ')

Examples

replaceSpaces('this\n   is     \ta    \rmessage') // 'this is a message'