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().
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 −
Here, my file name is demo250.js.
This will produce the following output on console −