replace space in javascript code example

Example 1: js replace space with underscore

var string = "my name";
string = string.replace(/ /g,"_"); //returns my_name

Example 2: js replace space

// replaces space with '_'
str = str.replace(/ /g, "_");
// or
str = str.split(' ').join('_');

Example 3: replace white spaces javascript

const name = 'Hi my name is Flavio'
name.replace(/\s/g, '') //HimynameisFlavio

Example 4: js replace all spaces

var replaced = str.replace(/ /g, '_');

Example 5: replace spaces with backslash js

input = "Hello my name is Luke"
inputWithoutSpaces = input.replace(/\s/g, "_"); // \s == space
console.log(inputWithoutSpaces); //Output: "Hello_my_name_is_Luke"