54
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript: 前後の空白を取り除く方法

Last updated at Posted at 2014-03-25
" aaa ".trim();// "aaa"

解説

String.trim()メソッドがJavascript1.8.1より実装されています。

IEで言うと9以降。Chrome,Firefoxに関しては今日現在の最新版であればすでに対応しているようです。safariは5以降だそうです、実機で試していないので断言はできませんが動くと思います。

IE9未満のブラウザには正規表現で自前で行う必要があります。

string.replace(/^\s+|\s+$/g,'');

以下のようにしておくことで、IE9未満でも他のブラウザと同様に冒頭のように使えるようになります。

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,'');
  };
}
54
49
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?