Reputation: 19049
Using replace(/\s+/g,"");
removes all spaces.
Using replace(" ","");
removes only the first space.
Why?
Upvotes: 2
Views: 122
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
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
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