This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

String.prototype.trim()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015년 7월⁩.

String 값의 trim() 메서드는 문자열 양 끝의 공백을 제거하면서 원본 문자열을 수정하지 않고 새로운 문자열을 반환합니다.

한쪽 끝의 공백만 제거한 새로운 문자열을 반환하려면 trimStart() 또는 trimEnd()를 사용하세요.

시도해 보기

const greeting = "   Hello world!   ";

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trim());
// Expected output: "Hello world!";

구문

js
trim()

매개변수

없음.

반환 값

시작과 끝에서 공백이 제거된 str을 나타내는 새로운 문자열입니다. 공백은 공백 문자와 줄 종결자로 정의됩니다.

str의 시작이나 끝에 어떠한 공백 문자가 없더라도, 새로운 문자열이 반환됩니다. 기본적으로 str의 복사본입니다.

예제

trim() 사용하기

아래 예제는 str 양 끝의 공백을 제거합니다.

js
const str = "   foo  ";
console.log(str.trim()); // 'foo'

명세서

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.trim

브라우저 호환성

같이 보기