Remove ALL white spaces from text
Eradicate all white spaces in a JavaScript string using .replace(/\s+/g, '')
:
Brace yourselves! No more spaces, tabs or newline characters, only a continuous barrage of characters.
Detailing your artillery
You're about to embark on a quest to free your strings from the tyranny of white spaces. Different forms of white space — spaces, tabs, and new line characters - hide in your strings and .replace()
is your weapon of choice.
Slaying with style: modern JavaScript
Newer versions of JavaScript introduce the .replaceAll()
method. However, it's a bit picky as .replaceAll()
does not accept a regex pattern. Stick with your .replace()
weapon for global regex operations.
Deciphering the weapon's blueprint
Every weapon bears a blueprint: here's what /\s+/g
implies:
\s
refers to any white space character including spaces, tabs, line breaks.+
ensures we hit multiple white spaces in a single shot.g
stands for global: it orders to attack all occurrences in the string.
Keeping a technology timeline
Be mindful of replaceAll()'s
limited browser support. Stick to .replace()
for older browser versions since it knocks out more targets globally.
Tackling the oddballs
Your quest will certainly be ridden with exceptions and alternative methods. Be prepared!
Empty strings aren't rogue
An empty string is your ally, not a foe! The .replace()
method leaves empty strings unaltered.
Attacking border outposts
Only need to clean the boundaries of your string? Call .trim()
for backup.
Simple replace()
isn't a marksman
If the target isn't a regex pattern, .replace()
only hits the first occurrence. Don't expect a massacre!
Was this article helpful?