Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour with spliting a string in Javascript

I am trying to do something relatively simple. I have a date in this format dd/MM/yyyy eg:

var newDate = "‎11‎/‎06‎/‎2015";

And I want to convert it to a date.

This code only works in Chrome and Firefox:

new Date(newDate)

In IE11 I get Nan

So I am trying to do this:

var parts = newDate.split("/");
var year = parts[2].trim();
var month = parts[1].trim();
var day = parts[0].trim();
var dt = new Date(Number(year), Number(month) - 1, Number(day));

Which should work, but I have encountered a very strange bug.

If you try this code:

function myFunction() {
  var newDate = "‎11‎/‎06‎/‎2015";
  var parts = newDate.split('/');
  var year = parts[2].trim();

  var a = year;
  var b = Number(year);
  var c = parseInt(year, 10);
  var d = parts;
  var n = a + "<br>" + b + "<br>" + c + "<br>" + d;
  document.getElementById("demo").innerHTML = n;
}
<p>Click the button to see the parse error.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

Then in IE it adds a mystery character and it prints out ý2015 and in chrome it prints out ?2015.

In fact the value of parts in IE is : ý11ý,ý06ý,ý2015 In Chrome: ?11?,?06?,?2015

I can't understand where these mystery characters come from! My original string is just "‎11‎/‎06‎/‎2015"

There seems to be no way for be to do something so simple, such as parsing an integer from a simple string.

Fiddle doesn't show the hidden characters but I believe they are still there because Number("2015") results in NaN as you can see clearly here Any ideas?

UPDATE

There are indeed hidden characters in the string, and after investigation I found out that they are created like this:

var date = new Date();
var dateToSave = date.toLocaleDateString();

but only in IE.

In Chrome or Firefox the output doesn't contain the U+200E left-to-right mark but in IE it does!

Removing toLocaleDateString() and replacing it with kendo.toString(selectedValue, "dd/MM/yyyy") fixed the problem.

For the record I also tried moment.js and the line: moment(selectedValue).format("DD/MM/YYYY") but for some reason in IE11 there was one hidden U+200E character at the very beginning of the result string.

like image 836
Nick Avatar asked Jun 11 '15 14:06

Nick


1 Answers

I ran "‎11‎/‎06‎/‎2015".split('').map(function(s){return s.charCodeAt(0)}) (to get the Unicode values) in my console, and found something interesting: [8206, 49, 49, 8206, 47, 8206, 48, 54, 8206, 47, 8206, 50, 48, 49, 53]

You have a U+200E left-to-right mark in there. I don't know how it got there.

Remove it, and you'll be fine.

Here, you can copy and paste the string from me: "11/06/2015".

like image 152
Scimonster Avatar answered Nov 09 '22 03:11

Scimonster