.Maui Blog

Javascript remove all spaces from a string

JavaScript provides the replace function, however, unlike other programming languages, does not replace all occurrences of a substring within another string, but only replaces the first occurrence.

So if we want to remove all spaces from a string in Javascript, or replace spaces with nothing, we must resort to a small regular expression in combination with the replace function.

var string = " m a  u i";
var nospace = string.replace(/ /g, ''); // "maui"

The same example should be used to replace a substring within another string, for example, if we want to replace all the “a” letters with another:

var string = "I ate pizza tonight.";
var newstring = string.replace(/a/g, 'x'); //I xte pizzx tonight.'.
Exit mobile version