String .trim() / trimStart() / trimEnd() Since: ES5(ECMAScript 2009)
Removes whitespace from the beginning and end of a string. Whitespace in the middle of the string is not removed.
Syntax
// Removes whitespace from both the beginning and end. string.trim() // Removes whitespace from the beginning only. string.trimStart() // Removes whitespace from the end only. string.trimEnd()
Methods
| Method | Description |
|---|---|
| trim() | Returns a new string with whitespace removed from both the beginning and end. |
| trimStart() | Returns a new string with whitespace removed from the beginning only. |
| trimEnd() | Returns a new string with whitespace removed from the end only. |
Sample Code
var str = " Hello World ";
// Removes whitespace from both the beginning and end.
console.log(str.trim()); // Outputs "Hello World".
// Removes whitespace from the beginning only.
console.log(str.trimStart()); // Outputs "Hello World ".
// Removes whitespace from the end only.
console.log(str.trimEnd()); // Outputs " Hello World".
// Whitespace in the middle of the string is preserved.
console.log(str.trim().length); // Outputs "11".
// Tabs and newlines are also treated as whitespace and removed.
var code = "\t\n Hello \n\t";
console.log(code.trim()); // Outputs "Hello".
// Useful for validating form input values.
var input = " ";
if (input.trim() === "") {
console.log("Field is empty"); // Detects input that contains only whitespace.
}
Overview
string.trim() is a method that removes whitespace characters from the beginning and end of a string. It targets not only regular spaces but also tabs, newlines, full-width spaces, and other whitespace characters. Whitespace in the middle of the string is not removed.
The most common use case is validating form input values. If a user accidentally types spaces at the beginning or end of their input, you can use string.trim() to remove them and get the correct value. Input that contains only whitespace can also be detected with input.trim() === "", making this an essential method for input validation.
Use string.trimStart() and string.trimEnd() when you need to remove whitespace from only one side. Neither method modifies the original string — both return a new string.
Browser Compatibility
3 or earlier ×
2.5 or earlier ×
4 or earlier ×
10 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.