Remove the whitespaces from a string using replace() in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 01-Sep-2020 11:12:29
Advertisements