1
0

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.

Internet Explorer 11 では Date#toLocaleString() の文字列に不可視な文字が含まれる

Last updated at Posted at 2015-12-16

現象

Date#toLocaleString() は、下記のように日付をその地域の文字列で返します。

var date = new Date();
console.log(date.toLocaleString()); // "‎2015‎年‎12‎月‎16‎日‎ ‎13:‎02‎:‎27"

この結果、一見ただの日付に見えますが、IE 11 では数字の前後に Left-to-Right マークが存在します。

// Left-to-Rightを「!」に置換
console.log(date.toLocaleString().replace(/\u200E/g, '!'));
//=> "!2015!年!12!月!16!日! !13!:!02!:!27"

※Left-to-Rightマーク(U+200E、HTMLでは‎または ‎): 文字の記述方向を示すコントロール文字(Wikipedia Left-to-right mark)

なお、Date#toLocaleDateString() でも同様です。

なにが起こるか

  • 文字列の長さ(String#length)がChromeなど他のブラウザと異なる
  • HTTPで送信(ajax / form submit)したときに文字‎として処理される

どうするべきか

文字列をそのまま表示する以外の目的でこのメソッドを使うべきではないでしょう。

特に年月日などの数字が欲しい場合に、この文字列をパースしようなどと考えてはいけません :feelsgood: :finnadie: :feelsgood:
(年:getFullYear()、月:getMonth()+1、日:getDate()を使います)

参考リンク

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?