9

I've ran into a possible bug with IE where calling the JavaScript .length function returns a value that is off by 1 if/when the string was derived from .toLocaleString().

var d = new Date();
var locale = navigator.language;
var month = d.toLocaleString(locale, { month: "long"});
// month.length will return the length of the month string +1 
//(eg: if month = "March", month.length will return 6.)

Interestingly, the code example of above will return true (in IE) for the following: (month[0] should be "M")

month[0] == "";
month[1] == "M";
month[2] == "a";
month[3] == "r";
month[4] == "c";
month[5] == "h";

In my particular case, this is causing a problem where I need to .slice() the month. Example: If the month is March, then IE will return "Ma" for month.slice(0,3) instead of "Mar".

Is this a known bug with IE? Is there a fix and/or workaround for this problem?

Run this fiddle in IE and Chrome/Firefox/Safari and notice how the month.length is wrong in IE.

My Environment:

OS: Win Server 2012 R2

IE Version: 11.0.9600.18231 (Update Versions: 11.0.29)

Locale: English/US

Community
  • 1
  • 1
Jed
  • 10,649
  • 19
  • 81
  • 125

1 Answers1

11

So, I stumbled upon this post toLocaleDateString error in IE 11

It appears it is caused by the toLocaleDateString function added extra LTR and RTL characters in IE11. One of the comments gave a regex replace function that is working for me.

month.replace(/[^ -~]/g,'');

Try adding that after you perform the .toLocaleDateString() and it should work. It worked for me.

Just another reason for us to despise IE.

Community
  • 1
  • 1
Alex Chance
  • 783
  • 4
  • 16
  • 2
    Also want to add [this question](http://stackoverflow.com/questions/25574963/ies-tolocalestring-has-strange-characters-in-results) as related for future readers. – Chatoyancy Mar 25 '16 at 19:26
  • "This is by design so the output text will flow properly when concatenated with other text." – Knu Mar 25 '16 at 23:24
  • Thank you so much ! I used a regex to check the date after a call to toLocaleDateString() and did not undestand why it won't work on IE11 -_- – François.M Dec 06 '17 at 21:00