Let’s say the following is our string with whitespace −
var fullName=" John Smith ";
Use replace() and set Regex in it to remove whitespaces.
Example
function removeSpacesAtTheBeginningAndTheEnd(name) {
return name.toString().replace(/^\s+|\s+$/g,'');
}
var fullName=" John Smith ";
var
valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName)
console.log(valueAfterRemovingSpace);To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo208.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo208.js John Smith