Replace Space And Hyphen With Underscore Javascript

Replace Space And Hyphen With Underscore Javascript

3 min read Jun 20, 2024
Replace Space And Hyphen With Underscore Javascript

Replace Space and Hyphen with Underscore in JavaScript

In this article, we'll explore how to replace spaces and hyphens with underscores in JavaScript. This is a common task when working with filenames, database keys, or any other string where spaces and hyphens are not allowed.

Understanding the replace() Method

JavaScript's replace() method is our primary tool for this task. It allows us to find and substitute specific characters within a string.

Here's a basic example:

let myString = "This is a sample string.";
let newString = myString.replace(" ", "_");
console.log(newString); // Output: This_is_a_sample_string.

In this code:

  • myString is our original string.
  • replace(" ", "_") replaces all spaces (" ") with underscores ("_").
  • newString stores the modified string.

Replacing Spaces and Hyphens

To replace both spaces and hyphens, we can use the replace() method with regular expressions:

let myString = "This-is-another-string.";
let newString = myString.replace(/[\s-]/g, "_");
console.log(newString); // Output: This_is_another_string.

In this example:

  • [\s-] is a regular expression that matches either a space (\s) or a hyphen (-).
  • g is a flag indicating a global search, replacing all occurrences in the string.

Alternative Method: Using split() and join()

Another approach is to use split() and join():

let myString = "Yet another-string with spaces.";
let words = myString.split(/[\s-]/);
let newString = words.join("_");
console.log(newString); // Output: Yet_another_string_with_spaces.

This method:

  • Splits the string into an array of words using the same regular expression as before.
  • Joins the array elements back into a string, using "_" as the separator.


Both methods achieve the same result. Choose whichever method suits your coding style and preference. Remember to test your code thoroughly to ensure you achieve the desired outcome.

Related Post