chris c
chris c

Reputation: 331

IndexOf not working with date tolocalestring in ie but ie supports it

So I have some code which works on other browsers but in IE it's not working. I can confirm by logging output to the browser that the indexOf function is supported and working because the console.log('array.indexOf(2) = ' + array.indexOf(2)); code outputs 0 in the console.

According to my logging output other values are correct and everything looks like it should work, but the code inside the if statement is never hit.

Here is an image of my javascript logging to the console Here is an image of my javascript logging to the console

I tried numerous things, which I have highlighted in the code like using .toString() and jQuery.inArray and also daySetting[0].includes

console.log('daySetting[0] = ' + daySetting[0]);

console.log('new Date().toLocaleString("en-us", { weekday: "short" }) = ' + new Date().toLocaleString('en-us', { weekday: 'short' }));

console.log('daySetting[0].indexOf(new Date().toLocaleString("en-us", { weekday: "short" })) = ' + daySetting.indexOf(new Date().toLocaleString('en-us', { weekday: 'short' })));

var array = [2, 9, 9]; //test array
console.log('array.indexOf(2) = ' + array.indexOf(2));

if (daySetting[0].toString().indexOf(new Date().toLocaleString('en-us', { weekday: 'short' })) !== -1) {
  //|| daySetting[0].includes(new Date().toLocaleString('en-us', { weekday: 'short' }))//tried the includes method and .toString() method
  //if (jQuery.inArray(new Date().toLocaleString('en-us', { weekday: 'short' }), daySetting) != -1) {//tried jquery in array
  console.log("dayHours = " + dayHours); //expecting this to be output
  continue; //code is inside a loop
}

I expect to see the code console.log("dayHours = " + dayHours); to be logged to the console but it is not. This works fine in other browsers but I just can't figure out what's going on.

Here is a fiddle of the code https://jsfiddle.net/q8pod2xj/1/

Upvotes: 0

Views: 70

Answers (1)

Sudhakar Ramasamy
Sudhakar Ramasamy

Reputation: 1759

Problem isn't with indexOf.

new Date().toLocaleString('en-us', { weekday: 'short' }) returns ' Thu' (length=4), has a space in 0th index. Avoided it using substr(1).

var theHours = "Mon: Open 9am - 5:30pm, Tues: Open 9am - 5:30pm, Wed: Open 9am - 5:30pm, Thurs: Open 9am - 5:30pm, Fri: Open 9am - 5:30pm, Sat: Open 9am - 5pm, Sun: Open 11am - 5pm";
var days = theHours.split(',');
for (var i = 0; i < days.length; i++) {
    var daySetting = days[i].split(/:(.+)/);
    var dayHours = daySetting[1];

    if (daySetting[0].indexOf(new Date().toLocaleString('en-us', { weekday: 'short' }).substr(1)) !== -1) {
        console.log("dayHours = " + dayHours); //expecting this to be output
        continue; //code is inside a loop
    }
}

Upvotes: 1

Related Questions