Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

internet explorer 11 - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...