- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove the whitespaces from a string using replace() in JavaScript?
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
Advertisements
To Continue Learning Please Login
Login with Google