String.prototype.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.
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()
はその文字列自身の値には影響を与えません(非破壊メソッド)。
Polyfill
ネイティブで使用できない場合、他のコードの前に次のコードを実行することにより 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'
仕様
ブラウザー実装状況
BCD tables only load in the browser
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.