admin管理员组

文章数量:1288078

I'm having trouble understanding what is going on with some JavaScript that seems to behave differently in Edge. Specifically boiled it down to:

var testi = new Date().toLocaleTimeString();
var len2 = testi.length;
alert(len2);

My length in Edge is 17, in Chrome and IE it's 10 There seems to be some phantom spaces in the string, it also screwed up my attempting to substring it.

/

FYI my Time Zone is US Central.

I'm having trouble understanding what is going on with some JavaScript that seems to behave differently in Edge. Specifically boiled it down to:

var testi = new Date().toLocaleTimeString();
var len2 = testi.length;
alert(len2);

My length in Edge is 17, in Chrome and IE it's 10 There seems to be some phantom spaces in the string, it also screwed up my attempting to substring it.

https://jsfiddle/m1m8h7ym/

FYI my Time Zone is US Central.

Share Improve this question asked Aug 19, 2015 at 14:58 AaronAaron 1,4891 gold badge18 silver badges33 bronze badges 2
  • Why do you want string operations on the result of toLocaleString when you can extract any part of the date object? – marekful Commented Aug 19, 2015 at 15:06
  • My goal was a user facing time string in the format 09:30 AM, and I didn't feel like doing the 24 hour to AM/PM and time zone conversion myself, so i striped the seconds off of toLocaleTimeString(), which led me to discover this JavaScript error (quirk?) This is some older code that with a few users upgrading to windows 10 we just started seeing. Been working great in IE, Chrome, and Firefox – Aaron Commented Aug 19, 2015 at 15:11
Add a ment  | 

1 Answer 1

Reset to default 15

Looks like Microsoft is slipping in the invisible left-to-right mark. This also occurs in IE11 in Edge mode. I figured this out by looping through each character in the string and passing it to encodeURIComponent()

var output = document.getElementById("output");
var testi = new Date().toLocaleTimeString();
var row;
for (var i = 0, len = testi.length; i < len; i++) {
    row = document.createElement("pre");
    row.innerHTML = encodeURIComponent(testi[i]);
    output.appendChild(row);
}
<div id="output"></div>

You could strip it out by removing it by its unicode, which can be captured in regex by the expression \u200E.

var output = document.getElementById("output");
var testi = new Date().toLocaleTimeString().replace(/\u200E/g,"");
var row;
for (var i = 0, len = testi.length; i < len; i++) {
    row = document.createElement("pre");
    row.innerHTML = encodeURIComponent(testi[i]);
    output.appendChild(row);
}
<div id="output"></div>

本文标签: Microsoft Edge javascript toLocaleTimeString incorrect spacingStack Overflow