--- title: String.prototype.trim() slug: Web/JavaScript/Reference/Global_Objects/String/trim tags: - ECMAScript 5 - JavaScript - Method - Prototype - Reference - String translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim ---
trim() メソッドは、文字列の両端の空白を削除します。このコンテクストでの空白には、空白文字(スペースやタブ、ノーブレークスペースなど)とすべての改行文字(LF や CR など)を含みます。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
str.trim()
呼び出し元の文字列の両端から空白を取り除いた新しい文字列です。
trim() メソッドは両端の空白を取り除いた文字列を返します。trim() はその文字列自身の値には影響を与えません(非破壊メソッド)。
ネイティブで使用できない場合、他のコードの前に次のコードを実行することにより String.trim() が使用可能になります。
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
trim() を使う以下の例は小文字の文字列 'foo' を表示します。
var orig = ' foo '; console.log(orig.trim()); // 'foo' // 片方からだけ空白を取り除く .trim() の例。 var orig = 'foo '; console.log(orig.trim()); // 'foo'
| 仕様書 |
|---|
| {{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}} |
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
{{Compat("javascript.builtins.String.trim")}}