Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. String .trim() / trimStart() / trimEnd()

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

MethodDescription
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

Chrome Chrome
49+
3 or earlier ×
Firefox Firefox
57+
2.5 or earlier ×
Safari Safari
18+
4 or earlier ×
Edge Edge
80+
11 or earlier ×
IE IE
11+
9 or earlier ×
Opera Opera
48+
10 or earlier ×
iOS Safari iOS Safari
18+
4 or earlier ×
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .