Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
JavaScript String trim()
In this tutorial, we will learn about the JavaScript String trim() method with the help of examples.
The trim() method removes whitespace from both ends of a string.
Example
const message = " JAVASCRIPT IS FUN ";
// remove leading and trailing whitespaces
const newMessage = message.trim();
console.log(newMessage);
// Output: JAVASCRIPT IS FUN
trim() Syntax
The syntax of trim() is:
str.trim()
Here, str is a string.
trim() Parameter
The trim() method does not take in any parameters.
trim() Return Value
- Returns a new string representing the
strstripped of whitespace from both ends.
Notes:
- Whitespace is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
- The
trim()method does not change the original string.
Example: Using trim()
let str = " foo ";
console.log(str.trim()); // 'foo'
// trim() removes whitespace only from the edges
let str1 = " A B C D ";
console.log(str1.trim()); // 'A B C D'
Output
foo A B C D
Did you find this article helpful?