Home > Back-end >  JS split(", ") works in Browser console but not in Node
JS split(", ") works in Browser console but not in Node

Time:01-31

I'm using Firefox, and tried this with node v14 and v17. I'm trying to parse a string into a date:

const extractThreadDate = (page: string): Date => {
      const $ = cheerio.load(page)
      const posthead = $("div .posthead")
      const postdate = $(".postdate", posthead)
      // format: 25/01/2010, 12:37
      const textDate = postdate.first().text().trim()
      console.log("1", textDate)
      const [dayDate, hourDate] = textDate.split(", ")
      console.log("2", [dayDate, hourDate])
      const [day, month, year] = dayDate.split("/").map(s => Number(s))
      console.log("3", [day, month, year])
      const [hour, minute] = hourDate.split(":").map(s => Number(s))
      console.log("4", [hour, minute])
      const date = new Date(year, month, day, hour, minute)
      return date
}

However the logs show the following:

1 25/01/2010, 12:37
2 [ '25/01/2010, 12:37', undefined ]
3 [ 25, 1, NaN ]

Any hints?

CodePudding user response:

You can regex all whitespace using /\s/g in JavaScript, so to match this, you could do .split(/,\s/g) rather than targeting arbitrary/specific whitespace characters.

CodePudding user response:

So, I did a sanity check and noticed that "25/01/2010, 12:37".split(", ") works correctly by itself. Weirded out, I put a fs.writeFileSync("hehehehe", textDate). Turns out there was a \u00a0 character instead of a space. Amazing. Who thought it'd be a good idea to have another whitespace? Whatever, that was it, split(",\u00a0") works fine.

The reason it worked is that when you copy it to the clipboard, it apparently gets converted into a regular whitespace.

  •  Tags:  
  • Related