Internet Explorer Returning Wrong Length of String [duplicate]

非 Y 不嫁゛ 提交于 2019-12-09 02:55:05

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/36225603/internet-explorer-returning-wrong-length-of-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!