Replace + with Space in JavaScript

This guide walks you through how to replace the + sign with a space in a string, a common requirement when dealing with URL query strings.

What is String Replacement?

You would use the String.prototype.replace() to search a string for a specified value, or a regular expression, and return a new string with the specified values replaced.

const queryString = 'name=John+Doe&age=30'; const withSpaces = queryString.replace(/\\+/g, ' '); console.log(withSpaces); // "name=John Doe&age=30"

Global Replacement Using Regular Expressions

To replace all occurrences of +, you should use a regular expression with a global flag (g).

const text = 'Hello+World+Again'; const newText = text.replace(/\\+/g, ' '); console.log(newText); // "Hello World Again"

Edge Cases

Be careful for edge cases where the + sign may be used in a context that should not be replaced.

const productCode = 'L+12345+X'; // Replace only the `+` that are between words const updatedCode = productCode.replace(/(\\b)\\+(\\b)/g, '$1 $2'); console.log(updatedCode); // "L+12345 X"

decodeURComponent

When dealing with URL parameters, spaces are often encoded as +. To convert them back to spaces, you might need to decode them first using decodeURIComponent.

const encoded = 'search=JavaScript+Tips'; const decoded = decodeURIComponent(encoded); const withSpaces = decoded.replace(/\\+/g, ' '); console.log(withSpaces); // "search=JavaScript Tips"

How to Deal with Different Encodings

When processing URLs or form data, spaces can be encoded as either + or %20. To normalize these to spaces, a two-step approach may be necessary: first, replace + with spaces, then decode the URI component.

function normalizeSpaces(encodedString) { const replacedPlus = encodedString.replace(/\+/g, ' '); return decodeURIComponent(replacedPlus); } const example = 'search=JavaScript+Tips%20and+Tricks'; console.log(normalizeSpaces(example)); // "search=JavaScript Tips and Tricks"

Function Wrapping for Reusability

To handle replacements consistently across an application, you can wrap the replacement logic in a function. This should help with maintainability and readability.

function replacePlusWithSpace(str) { return str.replace(/\+/g, ' '); } const query = 'name=Jane+Doe&action=edit'; console.log(replacePlusWithSpace(query)); // "name=Jane Doe&action=edit"

Advanced Replacement Functions

For complex replacement logic, you can pass a function to String.prototype.replace() instead of a string. This function can contain additional logic to determine what each match should be replaced with.

function complexReplace(match) { // Add any custom logic for the replacement. if (match === '+') { return ' '; // Replace '+' with a space. } // Other custom logic could go here. } const complexString = 'Complex+string+with+1+2+3'; const replacedString = complexString.replace(/\+/g, complexReplace); console.log(replacedString); // "Complex string with 1 2 3"

Let’s say we want to replace the + sign with a space, but only if it's not followed by a number. This kind of logic can be useful when trying to clean up text but where you also want to preserve certain patterns like C++ or algebraic expressions.

function selectiveReplace(match, p1, p2, offset, string) { // p1 is the plus sign, p2 is the following character if any. if (p1 === '+' && isNaN(parseInt(p2))) { return ' '; // Replace '+' with a space if it's not followed by a number. } else { return match; // Otherwise, keep the original match. } } const complexString = 'C++ is more complex+than JavaScript+3'; const replacedString = complexString.replace(/(\+)(.)/g, selectiveReplace); console.log(replacedString); // "C++ is more complex than JavaScript+3"

Here, the selectiveReplace function checks if the + sign is followed by a number. If not, it replaces the + with a space. This preserves instances like 'C++' or '+3' in our string while cleaning up other occurrences of the + sign.

Invite only

We're building the next generation of data visualization.