Explain Codes LogoExplain Codes Logo

Remove ALL white spaces from text

javascript
regex-patterns
string-manipulation
javascript-methods
Alex KataevbyAlex Kataev·Jan 3, 2025
TLDR

Eradicate all white spaces in a JavaScript string using .replace(/\s+/g, ''):

let spaceKiller = 'White spaces must die!'.replace(/\s+/g, ''); console.log(spaceKiller); // 'Whitespacesmustdie!'

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.

let frontierSweep = ' Witness the whitespace '.trim(); console.log(frontierSweep); // 'Witness the whitespace'

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!

let misguidedHit = 'One hit wonder'.replace(' ', ''); console.log(misguidedHit); // 'Onehit wonder'