This article explains how to remove spaces before and after a string in JavaScript .
How can I remove whitespace before and after a string?
You can easily remove whitespace before and after a string by using the trim() method.
trim removes whitespace before and after a string
There is a trim method to remove whitespace before and after a string .
string.trim();
This method removes whitespace from the beginning and end of a string.
Consecutive spaces in the string are replaced with a single space.
let str = " Hello World! ";
console.log(str.trim());
// Output: "Hello World!"
In the above sample, the string “Hello World!” is assigned to the variable str.
Next, we use the trim method to remove spaces before and after the string in the str variable, and display the results using the console.log() function. “Hello World!” will be displayed as the execution result.
summary
The following is a summary of how to remove spaces before and after a string.
- There is a trim method to remove whitespace before and after a string.
- The trim method removes whitespace from the beginning and end of a string.
- The trim method replaces consecutive spaces in a string with a single space.
You can easily remove whitespace before and after a string using the trim method.
The trim method can be used on objects other than strings, but care must be taken when using it on objects other than strings.
The trim method is not supported in browsers prior to IE9, so consider using it in a supported browser.
Comments