Recently, I was trying to parse the time portion of a date. I used split()
to chop time string into hours, minutes, seconds, etc. and attempted to parseInt()
the hour portion of the split array like so:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me to parse the current time</button>
<p id="demo"></p>
function myFunction() {
var str = new Date().toLocaleTimeString();
var parts= str.split(":");
var hour= parseInt(parts[0]);
document.getElementById("demo").innerHTML = parts+"
----
"+parts[0]+"
----
"+hour;}
//output:
//4,00,39,PM
//----
//4
//----
//NaN
</body>
</html>
The code above works in every other browser except Internet Explorer (11+) and Edge (all as of v 38.14393.0.0).
So what’s the problem? It turns out, that IE/Edge also includes some hidden formatting characters (in this case, one indicating left-to-right). Simply clearing that formatting string does the trick like so:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me to parse the current time</button>
<p id="demo"></p>
function myFunction() {
var str = new Date().toLocaleTimeString().replace(/\u200E/g, '');
var parts= str.split(":");
var hour= parseInt(parts[0]);
document.getElementById("demo").innerHTML = parts+"
----
"+parts[0]+"
----
"+hour;}
//output:
//4,00,39,PM
//----
//4
//----
//4
</body>
</html>