A lot of standard requirements are there in javascript related to the processing of strings. One such generic requirement is to replace multiple spaces with a single space in a javascript string. This article will discuss and demonstrate the same using various example illustrations.

Table of Contents:-

Replace multiple spaces with a single space using replace() and RegEx

Javascript’s replace() method replaces a particular pattern in the javascript with a replacement. The pattern can be a regular expression, a function, or a string.

Example:-

Replace multiple spaces with a single space from ” Javascript is the most popular language “

Code:-

let dummyString = "  Javascript   is the              most popular         language  ";
dummyString = dummyString.replace(/\s+/g, " ");
console.log(dummyString);

Output:-

 Javascript is the most popular language

Note: There is a space at the beginning and end of the output string.

Explanation:-

  • Here in the above code replace() function is used. The Regular expression is /\s+/g
  • /and / marks the beginning and end of a pattern.
  • \s+ matches at least one space character within the string.

If we want to remove the spaces from the start and end as well use:

Code:-

let dummyString = "  Javascript   is the              most popular         language  ";
dummyString = dummyString.trim().replace(/\s+/g, " ");
console.log(dummyString);

Output:-

Javascript is the most popular language

Explanation:-

  • The trim() method will remove the whitespaces from the start and end of the string.
  • Finally, the replace() method will remove the spaces in between the string.

Replace multiple spaces with a single space using split() and join()

Javascript’s split() method returns an array of substrings formed by splitting a given string.

Javascript’s join() method joins the elements of the array back into a string.

Example:-

Replace multiple spaces with a single space from ” Javascript is the most popular language “

Code:-

let dummyString = "  Javascript   is the              most popular         language  ";
dummyString = dummyString.trim().split(/[\s,\t,\n]+/).join(' ');
console.log(dummyString);

Output:-

Javascript is the most popular language

Explanation:-

  • The trim() method is used to remove all the spaces from the start and end of the string.
  • The split() method is used to split the string into an array of elements [ ‘Javascript’, ‘is’, ‘the’, ‘most’, ‘popular’, ‘language’ ]. The split is based on space, tab or new line character (\s,\t,\n)
  • Finally, join all the array elements using the join(‘ ‘) method separated by a single space to form a new string.

Read More:

I hope this article helped you to replace multiple spaces with a single space in a javascript string. Good Luck!!!