Skip to main content
made last paragraph more clear
Source Link
Ethan
  • 5k
  • 1
  • 30
  • 39

A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

// NOTE the possible initial and trailing spaces var str = " The dog has a long tail, and it is RED! " str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); // str -> "The dog has a long tail, and it is RED !" 

Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming even those into single spaces, like: " The ... RED! ", which is not what you will typically need.

A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

// NOTE the possible initial and trailing spaces var str = " The dog has a long tail, and it is RED! " str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); // str -> "The dog has a long tail, and it is RED !" 

Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was trimming even those into single spaces, like: " The ... RED! ", which is not what you will typically need.

A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

// NOTE the possible initial and trailing spaces var str = " The dog has a long tail, and it is RED! " str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); // str -> "The dog has a long tail, and it is RED !" 

Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.

Source Link
Ethan
  • 5k
  • 1
  • 30
  • 39

A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

// NOTE the possible initial and trailing spaces var str = " The dog has a long tail, and it is RED! " str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); // str -> "The dog has a long tail, and it is RED !" 

Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was trimming even those into single spaces, like: " The ... RED! ", which is not what you will typically need.