2

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

3
  • 3
    The g == global (also \s includes more than just " ") Commented Apr 8, 2014 at 13:02
  • 1
    /g it is global search. Commented Apr 8, 2014 at 13:02
  • Thanks all for explanations! Commented Apr 8, 2014 at 13:18

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.