Sometimes there can be extra spaces in between a string, so in this article, I have mentioned a few possible ways to replace all spaces from a string using Javascript(JS).

Using replaceAll()

replaceAll() Method is now supported in all modern browsers and can be used to replace space or any other special character from a string using Javascript.

The replaceAll method will return a new string where all occurrences of space have been replaced by the provided replacement. Since strings are immutable in Javascript, it doesn't change the original string and hence replaceAll() returns a new string.

Example to replace all space occurrence in Javascript using replaceAll()

const originalStr = 'Hello John wick';

const withoutSpaceStr = originalStr.replaceAll(' ', '-');
console.log(withoutSpaceStr); 
// Hello-John-wick

Output:

"Hello-John-wick"

replace-all-occurences-in-string-javascript-min

Using Replace()

While ReplaceAll() is perfect method to replace all spaces from string, you can also use string.replace(' ',newcharacter) to replace only first occurrence of space.

If you want to remove all occurrences of space from string using string.replace() method, then you will have to use Regex.

Example: 'originalString.replace(/ /g, '-');'

So, take a look at a complete example:

const originalStr = 'Hello John wick';

const withoutSpaceStr = originalStr.replace(/ /g, '-');
console.log(withoutSpaceStr); 
// Hello-John-wick

So, the output remains same as above example, but we are using Regex with .replace() to make the string remove all occurences of space.

In .replace() arguments, we are passing 2 argument

  1. A regular expression that matches all spaces (The forward slashes / / mark the beginning and end of the regular expression.)
  2.  Second argument is '-', replacement string/character for each regex match.

We replaced all spaces with a dash(-) in the above example. However, you could provide any replacement string.

You may also like to read:

Replace all occurrences in string using Javascript

How to remove quotation marks (double quotes) from string using jQuery or Javascript?

How to remove square brackets from string using javascript?

How do I remove last comma from string using jQuery or Javascript?

how to check if string is null or empty using jQuery or javascript?

How to compare two arrays using Javascript and get unmacthed elements?

How to format JSON date into valid date using javascript or jquery?