nicael
nicael

Reputation: 19049

Javascript - Removing spaces with replace()

Using replace(/\s+/g,""); removes all spaces.
Using replace(" ",""); removes only the first space.
Why?

Upvotes: 2

Views: 122

Answers (3)

ZaoTaoBao
ZaoTaoBao

Reputation: 2615

you can do sth like this:

function replaceAll( text, busca, reemplaza ){

  while (text.toString().indexOf(busca) != -1)

      text = text.toString().replace(busca,reemplaza);

  return text;

}

Upvotes: 1

user1921724
user1921724

Reputation:

The first one [replace(/\s+/g,"");] is a greedy Regular Expression search that will find all \s's globally.

The second one [replace()] is a string replacement and it replaces only the first match.

Upvotes: 3

Scimonster
Scimonster

Reputation: 33409

Because without the global flag, replace() only replaces the first occurrence.

EDIT: Your first function will also replace tabs and newlines (all whitespace), while the second only replaces literal spaces.

Upvotes: 2

Related Questions