 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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 extra spaces in string JavaScript?
To remove extra spaces, you need to use trim() along with regular expressions. Following is our string with spaces before applying trim() −
var sentence="My name is John Smith ";
Now, we will remove the extra spaces as in the below code −
Example
var sentence="My name is John Smith "; console.log("The actual value="); console.log(sentence); var originalSentence = sentence.replace(/\s+/g,'').trim(); var afterRemovingTheSpace=originalSentence.trim(); console.log("After removing the spaces="); console.log(afterRemovingTheSpace); To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo90.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo90.js The actual value= My name is John Smith After removing the spaces= MynameisJohnSmith
Advertisements
 