Replace all spaces in a string with '+'
To convert all spaces in a string to '+' in JavaScript, use the .replace()
method and the regex notation / /g
as follows:
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:
Transforming a parade of spaces
To replace multiple consecutive spaces with a single '+' symbol, include a +
quantifier in your regex pattern:
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 '+':
Refreshing with replaceAll
.replaceAll()
is a recent addition (ES2021) to JavaScript, specifically for replacing all occurrences of a substring without the need for regex:
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
:
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.
Was this article helpful?