-1

I have a string that needs to be cast into a date. In IE, my string has an unknown character in it, and it says invalid date when I cast it.

When I run

var dateString = $('#DueDate').val()
for(var i = 0; i < dateString.length; i++){console.log(dateString[i]);}

this is the output:

// empty line that I can't format in Stack overflow correctly
0
1

/

0
1

/

2
0
1
2

And dateString.length outputs 15. These characters cannot be spaces because dateString.valueOf() outputs "‎01‎/‎01‎/‎2012"

Also, if I copy and paste where these special characters should be from the control itself into the IE console, the Developer tools window freezes.... If I backspace from the control in the right places, it works fine (presumably because the special characters aren't there anymore). How can I search for and remove this character?

Conner
  • 352
  • 4
  • 10
  • see this https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript – Crappy Nov 29 '17 at 17:27
  • @Crappy OP does not know what the character actually is, so specifically targeting it with `replace` may not be their best option. – Tyler Roper Nov 29 '17 at 17:39
  • Thanks to @Santi: it was https://en.wikipedia.org/wiki/Left-to-right_mark – Conner Nov 29 '17 at 17:53

1 Answers1

1

How can I search for and remove this character?

You could utilize a regular expression.

The following will remove anything that isn't a number or a /:

var dateString = '12___/15___/20_17_xxx';         // Poorly-formatted date string
dateString = dateString.replace(/[^0-9/]/g, "");  // 12/15/2017

var date = new Date(dateString);                  // Cast as date
console.log(date);                                // 2017-12-15T05:00:00.000Z

If you'd like some more information about what the "weird" character may be, you can loop through the contents of the string and log each character code to the console:

var str = "Hello!";
for (var i = 0, len = str.length; i < len; i++) {
  console.log(str.charAt(i) + ": " + str.charCodeAt(i));
}
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56