10 Ways to replace Spaces in JavaScript


In the blogpost, we’ll learn multiple ways to replace (white) spaces in JavaScript. We’ll dive into various string functions, regex, and some array functions, we can use for this task. And then learn some common mistakes we could do, and cement our understanding with a fun practice question.

Techniques discussed are not just about replacing spaces; they’re about understanding string manipulation in JavaScript to make your code more efficient and your applications more dynamic.

Lets dive in! 👨‍💻


Ways to replace (white) spaces in JavaScript

Lets see various techniques to convert JavaScript Object to Map.

Using String.replace() to replace only first occurrence

The String.replace() method in JavaScript is used to search for a pattern in a string and replace it with a specified replacement string. When the pattern is a string, replace() only targets the first occurrence of that pattern.

This method is ideal to replace only the first occurrence of a space in a string.

  • In following code, "hello world" is the original string. The replace() method looks for the first space (" ") and replaces it with an underscore ("_"). As a result, "hello world" becomes "hello_world", with only the first space being replaced.
String.replace(): only first occurrence (JavaScript)
const originalString = "hello world. Do not remove space here.";
const replacedString = originalString.replace(" ", "_");
console.log(replacedString);  
// Output: "hello_world. Do not remove space here."

Using String.replace() with Global Flag to replace all space occurrences

To replace all occurrences of a pattern in a string, you can use a regular expression with the global (g) flag. This flag tells the replace() method to search for all matches in the string, not just the first one.

Ideal to replace every space in a string, not just the first.

  • In following code, / /g is a regular expression where the space character (" ") is the pattern and g is the global flag.
  • The replace() method uses this regex to find and replace all spaces with underscores.
String.replace(): global occurrences (JavaScript)
const originalString =
  "hello world. Also Remove Spaces Here";

// Regular expression for a space with a global flag
const regex = / /g;
const replacedString = originalString.replace(regex, "_");

console.log(replacedString);
// Output: "hello_world._Also_Remove_Spaces_Here"

Using String.replaceAll() to replace all occurrences without Regex

The String.replaceAll() method was introduced in ES2021 (ECMAScript 2021) as a more intuitive way to replace all occurrences of a pattern in a string, without needing to use a regular expression.

Ideal, to replace all occurrences of a particular substring (like a space) with another substring (like an underscore).

  • In following example, replaceAll() method is used to replace all instances of the space character with underscores.
  • Regex overload of the function can also be used though.
String.replaceAll(): global without regex (JavaScript)
const originalString = 
    "hello world. Also    Remove Spaces Here";

const replacedString = originalString.replaceAll(" ", "_");
// or even regex could have been used in place of space:
// const replacedString = originalString.replaceAll(/ /g, "_");

console.log(replacedString);
// Output: "hello_world._Also____Remove_Spaces_Here"

Using String.split() and Array.join()

This technique involves two main methods: split() and join().

The split() method divides a string into an ordered list of substrings by separating it at each occurrence of a specified separator string (in this case, a space) and returns an array of these substrings.

The join() method then combines all elements of the array into a single string, inserting a specified separator (an underscore) between each element.

Useful when you need to process individual words or segments of a string before joining them back together.

  • In following example, originalString is split into an array using split(" ").
  • Then, join("_") combines these elements into a single string, inserting an underscore between each word.
String.split() & Array.join() (JavaScript)
const originalString = 
    "hello world. Also    Remove Spaces Here";

// Splitting by space
const wordsArray = originalString.split(" ");
console.log(wordsArray);
//Output: ['hello', 'world.','Also','', '','','Remove','Spaces','Here']

// Joining with underscore
const joinedString = wordsArray.join("_");
console.log(joinedString); 
// Output: "hello_world._Also____Remove_Spaces_Here"

Regex \s to match all whitespaces (spaces, new lines & tabs)

The \s in a regular expression represents any whitespace character (including spaces, tabs, and newlines). When used with the replace() method and the global flag (g), it can replace all kinds of whitespace in a string with a specified replacement.

Ideal when the goal is to replace not just regular spaces but all types of whitespace in a string.

  • In following example, /\s/g is a regex that matches every whitespace characters (multiple \n, \t, ' ') our string. And all of them are easily replaced by ‘_’.
Whitespaces regex (JavaScript)
// 💩 Nasty combination of \n,\t and ' '.
const originalString = 
    "\thello world.\n Also\t Remove Spaces         Here\n";
    
const replacedString = originalString.replace(/\s/g, "_");

console.log(replacedString); 
// Output: "_hello_world.__Also__Remove_Spaces_________Here_"

Regex \s+ to match all consecutive whitespaces (spaces, new lines & tabs)

With just a + sign extra in our regex, the \s+ regex replaces consecutive whitespace character (including spaces, tabs, and newlines).

Ideal when the goal is to replace consecutive whitespaces in a string.

  • In following example, /\s+/g is a regex that matches every consecutive whitespace characters (multiple \n, \t, ' ') our string and replaces with single ‘_’.
Consecutive whitespaces regex (JavaScript)
// 💩 Nasty combination of \n,\t and ' '.
const originalString = 
    "\thello world.\n Also\t Remove Spaces         Here\n";

// Note the `+` in regex.
const replacedString = originalString.replace(/\s+/g, "_");

console.log(replacedString); 
// Output: "_hello_world._Also_Remove_Spaces_Here_"

Using String.replace() with a custom function

The replace() method can also take a function as its second argument. This function is called for each match, and the returned value from the function is used as the replacement string. This allows for more dynamic and complex logic in the replacement process.

Ideal when the replacement logic is not straightforward and depends on the context or content of each match.

  • In following code, the function passed to replace() checks each whitespace (using /\s/g as explained in previous section) and replaces it an emoji respective to the type of whitespace character.
String.replace() with custom function (JavaScript)
const originalString = "hello universe  !\ncant\tbreathe!";

const replacedString = originalString.replace(
  // regex for whitespace chars (\n,\t,' ')
  /\s/g,
  // Add custom logic for replacement
  (match) => {
    if (match === " ") {
      return "🚀";
    } else if (match === "\n") {
      return "🆕";
    } else if (match === "\t") {
      return "💊";
    } else {
      return match;
    }
  },
);

console.log(replacedString);
// Output: "hello🚀universe🚀🚀!🆕cant💊breathe!

Chaining String methods for multiple string transformations

We can chain multiple string methods to perform complex transformations in a concisely. Like trim(), replace(), and toLowerCase() can be combined to achieve specific formatting goals.

Ideal to perform several operations on a string in a specific order, such as trimming whitespace, changing case, and replacing characters.

  • In following example, trim() is first used to remove any leading and trailing spaces from the string " Hello World ".
  • The toLowerCase() method then converts all characters to lowercase, resulting in "hello world".
  • Finally, replace(/ /g, "_") replaces all spaces with underscores, producing "hello_world".
Chaining string transformations (JavaScript)
const originalString = " Hello World ";

const formattedString = originalString
  .trim()
  .toLowerCase()
  .replace(/ /g, "_");

console.log(formattedString); // Output: "hello_world"

Using Array.map() with Strings

Array.map() method creates a new array populated with the results of calling a provided function on every element in the calling array. When combined with string manipulation, this method can be used to process each character or segment of a string individually.

Ideal for situations where you need to apply a specific transformation or set of rules to each individual character or segment of a string.

  • In following example, "hello world" is first converted into an array of its characters using split("").
  • The map() function is then used to iterate over each character, replacing spaces with underscores.
  • Finally, join("") recombines the array elements into a single string, resulting in "hello_world".
Array.map() with strings (JavaScript)
const originalString = "hello world";
const arrayFromString = originalString.split(""); // Convert to array
const processedArray = arrayFromString.map(character => {
  return character === " " ? "_" : character;
});
const rejoinedString = processedArray.join("");
console.log(rejoinedString); // Output: "hello_world"

Replacing spaces in Template Literals for dynamic strings

Template literals in JavaScript allow for the creation of strings with embedded expressions. These literals provide an easier way to build strings, especially when incorporating variables and expressions. You can use string methods directly on template literals for further manipulation.

Ideal when dealing with strings that are constructed dynamically and require subsequent space replacement.

  • In following code, a template literal is used to create a greeting string that includes the variable name.
  • The replace() method with the global flag is then used to replace all spaces in the template literal with underscores.
Template Literals (JavaScript)
const name = "John Doe";
const greeting = `Hello ${name}`;
const formattedGreeting = greeting.replace(/ /g, "_");
console.log(formattedGreeting); // Output: "Hello_John_Doe"

Tips & errors while replacing white spaces in JavaScript

  • Global regex flag: Ensure you use the global flag (/ /g) when you want to replace all occurrences in a string. Else only 1 occurence replaced.
  • Consecutive vs every match replacements: Regex /\s+/g can replace consecutive whitespaces with a single replacement string, but regex /\s/g replaces every match with replacement string.
  • Dealing with different whitespace characters (tabs, newlines): Be specific in your regular expressions to match the exact type of whitespace you want to replace.
  • Performance considerations:
    • Consider the size of your input data; some methods may be more efficient than others for specific use cases.
    • Avoid excessive string conversions (e.g., from string to array and back) for large inputs.
    • Use the appropriate method for your environment, considering compatibility issues with older JavaScript engines.

🧪Practice Coding Problem: Space Launch 3️⃣,2️⃣,1️⃣,🚀.

In the spirit of Test Driven Learning ( 😁), lets test our understanding by solving a problem.

Write a JavaScript function that transforms any string by replacing each set of consecutive spaces with an emoji. The emoji replacement follows a cyclic pattern: for the first set of consecutive spaces, use 1️⃣; for the second, 2️⃣; for the third, 3️⃣; and for the fourth, 🚀. Then, repeat this cycle for subsequent sets of consecutive spaces.

  • The input string consists only of alphabets and spaces.
  • Consecutive spaces, regardless of the count, are replaced with a single emoji.
  • The function handles empty strings and strings without consecutive spaces.
Problem (JavaScript)
function galacticSpaceEmojifier(str) {
  // > > > 👉 Write code here 👈 < < <
}

console.log(galacticSpaceEmojifier("Ready for   launch")); 
// Output: "Ready1️⃣for2️⃣launch"

console.log(galacticSpaceEmojifier("T minus  10   seconds to  launch")); 
// Output: "T1️⃣minus2️⃣103️⃣seconds🚀to1️⃣launch"

console.log(galacticSpaceEmojifier("3   2  1  Launch !")); 
// Output: "31️⃣22️⃣13️⃣Launch🚀"

console.log(galacticSpaceEmojifier("")); 
// Output: ""

console.log(galacticSpaceEmojifier("    ")); 
// Output:️ "1️⃣"

console.log(galacticSpaceEmojifier("Exploring the vast universe")); 
// Output: "Exploring1️⃣the2️⃣vast3️⃣universe"
Please attempt before seeing the Answer:
JavaScript
function galacticSpaceEmojifier(str) {
    let result = '';
    let spaceCount = 0;
    let emojiIndex = 0;
    const emojis = ['1️⃣', '2️⃣', '3️⃣', '🚀'];

    for (let i = 0; i < str.length; i++) {
        if (str[i] === ' ') {
            spaceCount++;
            continue;
        }

        if (spaceCount > 0) {
            result += emojis[emojiIndex];
            emojiIndex = (emojiIndex + 1) % emojis.length;
            spaceCount = 0;
        }
        result += str[i];
    }

    // Add emoji for trailing spaces
    if (spaceCount > 0) {
        result += emojis[emojiIndex];
    }

    return result;
}

Explanation:

  • The function galacticSpaceEmojifier iterates over the characters in the input string str.
  • It counts consecutive spaces (spaceCount). When a non-space character is reached, the function checks if there were any spaces before it.
  • If there were spaces (spaceCount > 0), it adds the next emoji in the cycle to result.
  • The emojiIndex keeps track of which emoji to use next and cycles through the emojis array.
  • After adding an emoji or encountering a non-space character, spaceCount is reset to 0.
  • The function also handles trailing spaces, adding an emoji if the string ends with spaces.
  • The final result is a string where each set of consecutive spaces is replaced with a cyclically selected emoji, adding a playful and thematic element to the text.

Now you are an expert in replacing all (white)spaces in your JavaScript strings.

Keep learning, and keep coding! 🚀👨‍💻

Scroll to Top