JavaScript Replace Spaces

If you are working with JavaScript, you may encounter a situation where you need to replace spaces in a string with another character. This can be useful for formatting, encoding, or sanitizing your data. But how do you do it?

In this blog post, I will show you how.

  • Use a single space to replace spaces
  • Use underscores to replace spaces
  • Use hyphens to replace spaces
  • Use %20 in JavaScript to replace spaces in URLs
  • Use line breaks to replace spaces
  • Replace spaces and special characters
  • Use a space to replace the comma
  • Use a space to replace the newline

Let's get started.

JavaScript string replace() method

The JavaScript replace() method is mostly used to replace the spaces in this article. So here is a quick introduction to the replace() method. The replace() method in JavaScript is used to replace a specified substring or pattern with another substring. It operates on strings and provides a powerful way to manipulate and modify text content.

JavaScript replace method

Replace multiple spaces with a single space

If you want to replace many spaces with one space, you can use a special method called regular expressions. Regular expressions let you find and change patterns of text easily. Here is how you can use regular expressions to change multiple spaces into one space.

const stringWithMultipleSpaces = "JavaScript      runs     everywhere            on    everything!";
const stringWithSingleSpace = stringWithMultipleSpaces.replace(/\s+/g, ' ');
console.log(stringWithSingleSpace);
// Output: "JavaScript runs everywhere on everything!"

This code snippet utilizes the JavaScript replace() method and a regular expression (/\s+/g) to match one or more spaces globally in the string, transforming them into a single space.

Replace spaces with underscores

Sometimes you need to use underscores in your text. For example, you might want to separate words or make them look like code. In that case, you can use two methods: split() and JavaScript join(). Split lets you break a text into smaller parts. JavaScript join() method lets you put them back together. 

const stringWithSpaces = "JavaScript runs everywhere on everything!";
const stringWithUnderscores = stringWithSpaces.split(' ').join('_');
console.log(stringWithUnderscores);
// Output: "JavaScript_runs_everywhere_on_everything!"

This enchantment splits the string at each space and then rejoins the parts with underscores, offering a seamless text transformation.

Replace spaces with hyphens (-)

If you like using hyphens in your code, you need the replaceAll() method.

const stringWithSpaces = "JavaScript runs everywhere on everything!";
const stringWithHyphens = stringWithSpaces.replaceAll(' ', '-');
console.log(stringWithHyphens);
// Output: "JavaScript-runs-everywhere-on-everything!"

In this snippet, every space is replaced with a hyphen. Using this approach, you can build readable URLs.

Replace space with %20 in JavaScript for URLs

To replace spaces with %20 in JavaScript, you can use the replace() method along with a regular expression. This is commonly done when creating URL-encoded strings. Here's an example code snippet.

const originalString = "Replace spaces with %20 in JavaScript";
const urlEncodedString = originalString.replace(/ /g, '%20');
console.log(urlEncodedString);
// Output: "Replace%20spaces%20with%20%20%20in%20JavaScript"

This JavaScript code replaces spaces in the "originalString" with "%20", creating "urlEncodedString," and then logs the result to the browser console. This is a common technique used in web development when constructing URLs to ensure that spaces are properly encoded for use in a URL.

Replace spaces with line breaks (\n)

Do you want to use line breaks instead of spaces in your text? You can do that easily with the replace() method. This method lets you replace any character or string with another one. For example, you can replace all the spaces with "\n" to create a new line. This way, you can format your text the way you want. 

const stringWithSpaces = "JavaScript runs everywhere on everything!";
const stringWithLineBreaks = stringWithSpaces.replace(/ /g, '\n');
console.log(stringWithLineBreaks);
/* Output:
JavaScript
runs
everywhere
on
everything!
*/

This snippet swaps spaces into a JavaScript multiline string, allowing you to display each word on the new line.

Replace spaces and special characters

When spaces and special characters are to be replaced by a common symbol like an underscore ( _ ), the replace() method becomes your trusted option.

const stringWithSpaces = "Replace! Spaces@ with# a$ common% symbol";
const cleanedString = stringWithSpaces.replace(/[^\w\s]/g, '_');
console.log(cleanedString);
// Output: "Replace_ Spaces_ with_ a_ common_ symbol"

This script transforms any text into a clean version. It replaces symbols and punctuation (except spaces) with underscores. This creates a perfect string.

Replace the comma with a space

When the need arises to replace a string with commas and spaces, the replace() method again proves its capability.

const stringWithCommas = "Replace, commas, with, spaces";
const stringWithSpaces = stringWithCommas.replace(/,/g, ' ');
console.log(stringWithSpaces);
// Output: "Replace  commas  with  spaces"

In this snippet, every comma is gracefully replaced with a space, providing a cleaner and more readable string.

Replace newline with space

When newline (\n) characters disrupt your string's harmony. The replace() method comes to the rescue.

const stringWithNewlines = "JavaScript runs everywhere\n on everything!\n";
const stringWithSpaces = stringWithNewlines.replace(/\n/g, ' ');
console.log(stringWithSpaces);
// Output: "JavaScript runs everywhere  on everything!"

This script transforms each newline character into a space, preserving the string's coherence.

Conclusion

In this blog post, you have learned how to use JavaScript to replace spaces in different scenarios. We have seen how to use a single space, underscores, hyphens, %20, line breaks, and regular expressions to replace spaces and special characters. You have also learned how to use a space to replace commas and newline characters.

These techniques can help you manipulate strings and format them according to your needs. I hope you learned something new from this article.

If you have any questions or feedback, please leave a comment below.