Explain Codes LogoExplain Codes Logo

Replace all spaces in a string with '+'

javascript
regex
string-manipulation
performance
Nikita BarsukovbyNikita Barsukov·Oct 26, 2024
TLDR

To convert all spaces in a string to '+' in JavaScript, use the .replace() method and the regex notation / /g as follows:

let newStr = "Your string here".replace(/ /g, '+');

The / /g regex and global flag, /g, ensure every space transforms into a '+'.

Deep dive into different spaces

Not all spaces in JavaScript are created equal. There's the regular space, the tab (\t), and the newline (\n) character. If you want to replace all these with '+', use the \s in your regex match:

let newStr = "Your string here".replace(/\s/g, '+'); // Even the elusive spaces can't escape!

Transforming a parade of spaces

To replace multiple consecutive spaces with a single '+' symbol, include a + quantifier in your regex pattern:

let newStr = "Your string here".replace(/\s+/g, '+'); //No more congo line of spaces!

This will condense a sequence of whitespace characters down to a single '+'.

Regex-free alternatives

If regex seems like reading encrypted hieroglyphs, JavaScript offers other methods to replace spaces. A combo move with the .split() and .join() methods can also replace spaces with '+':

let newStr = "Your string here".split(' ').join('+'); // A split decision wasn't this simple before!

Refreshing with replaceAll

.replaceAll() is a recent addition (ES2021) to JavaScript, specifically for replacing all occurrences of a substring without the need for regex:

let newStr = "Your string here".replaceAll(' ', '+'); // Because changing all is 'all' we need!

In case you want to avoid regex patterns, this approach is more readable and user-intuitive.

Squaring up with URL encoding

In the context of URL encoding, spaces are usually replaced with '+' or %20. Implementing encodeURIComponent can help with proper URL encoding, which encodes spaces as %20:

let url = encodeURIComponent("Your string here"); // Turns spaces into flyspace!

When spaces need to be specifically encoded as '+', use .replace() or .replaceAll().

Trading off between methods

Consider the performance trade-off when selecting your method. While the regex solutions with .replace() might clock in faster, they can seem complex to beginners. On the other hand, .split().join() or .replaceAll() offer easy readability but with a slight overhead cost.