Skip to content

Instantly share code, notes, and snippets.

@marioblas
Last active August 29, 2015 13:59
Show Gist options
  • Save marioblas/81883cf2b96ebf6e5989 to your computer and use it in GitHub Desktop.
Save marioblas/81883cf2b96ebf6e5989 to your computer and use it in GitHub Desktop.
Javascript - Remove or replace spaces from a string
/**
* Remove spaces from a string.
*
* Info: http://stackoverflow.com/questions/5963182/how-to-remove-spaces-from-a-string-using-javascript
*/
str = str.replace(/\s+/g, '');
/**
* In the first regex, each space character is being replaced, character by character, with the empty string.
* In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.
*
* Info: http://stackoverflow.com/questions/5964373/is-there-a-difference-between-s-g-and-s-g
*/
' A B C D EF '.replace(/\s/g, '#') // ##A#B##C###D#EF#
' A B C D EF '.replace(/\s+/g, '#') // #A#B#C#D#EF#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment