add underscore between words javascript

To add underscores between words in a JavaScript string, effectively replacing spaces with underscores, you can use the replace() or replaceAll() methods, or a combination of split() and join().

1. Using replace() with a Regular Expression:

This method uses a regular expression to find all occurrences of spaces and replaces them with an underscore. The /g flag ensures a global replacement (all occurrences, not just the first).

JavaScript

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

2. Using replaceAll():

The replaceAll() method directly replaces all occurrences of a specified substring with another.

JavaScript

let str = "Another example string";
let result = str.replaceAll(" ", "_");
console.log(result); // Output: Another_example_string

3. Using split() and join():

This method first splits the string into an array of words using space as a delimiter, and then joins the array elements back into a string using an underscore as the separator.

JavaScript

let str = "Words separated by spaces";
let result = str.split(" ").join("_");
console.log(result); // Output: Words_separated_by_spaces



Leave a Reply