JavaScript String trim()
Summary: in this tutorial, you’ll learn how to use the JavaScript trim() method to remove whitespace characters from both ends of a string.
Introduction to the JavaScript trim() method
The String.prototype.trim()returns a new string stripped of whitespace characters from beginning and end of a string:
let resultString = str.trim();Code language: JavaScript (javascript)
The whitespace characters are space, tab, no-break space, etc.
Note that the trim() method doesn’t change the original string.
To remove whitespace characters from the beginning or from the end of a string only, you use the trimStart() or trimEnd() method.
JavaScript trim() example
The following example shows how to use the trim() to remove whitespace from both sides of a string:
let str = ' JS trim ';
let result = str.trim();console.log(result);
Code language: JavaScript (javascript)
Output:
"JS trim"Code language: JSON / JSON with Comments (json)
Summary
- Use the
trim()to remove whitespace characters from both ends of a string.