
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Remove all whitespaces from string - JavaScript
- Java Program to Remove All Whitespaces from a String
- Golang program to remove all whitespaces from a string
- C# Program to remove whitespaces in a string
- How to replace duplicate whitespaces in a String in Kotlin?
- Shedding a string off whitespaces in JavaScript
- Delete all whitespaces from a String in Java
- How to remove “,” from a string in JavaScript
- How to replace all dots in a string using JavaScript?
- How to replace string using JavaScript RegExp?
- Remove characters from a string contained in another string with JavaScript?
- Remove new lines from a string and replace with one empty space PHP?
- Update all rows in MySQL and remove all the unnecessary whitespaces in and around the string?
- How to remove html tags from a string in JavaScript?
- Remove elements from a queue using Javascript

Advertisements