
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
- Related Questions & Answers
- C program to remove extra spaces using string concepts.
- Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?
- Remove spaces from std::string in C++
- C++ Program to remove spaces from a string?
- Trim (Remove leading and trailing spaces) a string in C#
- Java Program to remove all white spaces from a String.
- Trim a string in Java to remove leading and trailing spaces
- C program to remove spaces in a sentence using string concepts.
- Find longest string in array (excluding spaces) JavaScript
- Finding number of spaces in a string JavaScript
- How to remove spaces at the end in string vectors in R?
- Split the sentences by comma and remove surrounding spaces - JavaScript?
- How to remove double or more spaces from a string in MySQL?
- How to write a Regular Expression in JavaScript to remove spaces?
- Removing all spaces from a string using JavaScript
Advertisements