Let’s say the following is our string −
var sentence = "My Name is David Miller I live in AUS";
To replace spaces in the above string with underscore, use split() along with join().
Example
Following is the code −
var sentence = "My Name is David Miller I live in AUS"; var withUnderscore = sentence.split(' ').join('_'); console.log("The actual result=") console.log(sentence); console.log("After replacing the space with underscore=") console.log(withUnderscore);
To run the above program, you need to use below command which is as follows −
node fileName.js
Here, my file name is demo250.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo250.js The actual result= My Name is David Miller I live in AUS After replacing the space with underscore= My_Name_is_David_Miller_I_live_in_AUS