How to Replace Spaces with Underscores in Javascript

Replacing Spaces with Underscores in JavaScript Example tutorial you will learn how to replace space with underscore in javascript;

In Javascript we can use the String.replace and String.replaceAll method to replace all spaces with underscores in a JavaScript string.

Example 1:

// Supported in IE 6-11
const str = 'this is test string';
const strUnderscores = str.replace(/ /g, '_');

console.log(strUnderscores); //this_is_test_string

The regular expression / / matches a whitespace character.

We have added the g (global) flag to the regex, which makes the regular expression match all whitespace characters in the string, instead of just the first one.

Example 2:

The replaceAll method returns a new string with all whitespace characters replaced by underscores.

// Not Supported in IE 6-11
const str = 'this is test string';
const strUnderscores = str.replaceAll(' ', '_');

console.log(strUnderscores); //this_is_test_string

Example 3:

For replacing all whitespaces with underscores you can use the split and join methods of javascript;

// Supported in IE 6-11
const str = 'this is test string';
const strUnderscores = str.split(' ').join('_')

console.log(strUnderscores); //this_is_test_string

Example 4:

If you have more then whitespaces between the string and you want only one unserscore then you need to put the replace method with regex. let see

// Supported in IE 6-11
const str = 'this    is test     string';
const strUnderscores = str.replace(/\s+/g, '_')

console.log(strUnderscores); //this_is_test_string

I hope these examples help you to replace the whitespaces with underscores in javascript;