Replace All Space With Underscore In Javascript

Replace All Space With Underscore In Javascript

2 min read Jun 20, 2024
Replace All Space With Underscore In Javascript

Replace All Spaces with Underscores in JavaScript

This article will guide you through the process of replacing all spaces within a string with underscores using JavaScript. We'll explore various methods and provide code examples for each.

Using replace method with regular expression

The replace() method is the most common way to replace characters within a string. By using a regular expression, you can target all occurrences of a specific character, in our case, spaces.

const str = "This is a string with spaces";

const newStr = str.replace(/ /g, '_');

console.log(newStr); // Output: This_is_a_string_with_spaces

In this code:

  • / /g: This is a regular expression that matches all spaces ( ) globally (g).
  • _: This is the replacement character, the underscore (_).

Using split and join methods

Another approach is to split the string based on spaces, then join the resulting array using underscores as the separator.

const str = "This is a string with spaces";

const newStr = str.split(' ').join('_');

console.log(newStr); // Output: This_is_a_string_with_spaces

Here:

  • split(' '): This splits the string into an array of words, using spaces as the delimiter.
  • join('_'): This joins the elements of the array back into a string, using underscores as the separator.

Which method to choose?

Both methods achieve the same result. The replace() method with a regular expression might be slightly more efficient, especially for large strings. However, the split and join approach is more readable for beginners.

Ultimately, choose the method that best suits your needs and coding style.

Related Post