Search code examples
reactjsstringdateintstartswith

How to check if a variable has certain symbols in React?


A new React developer here!

I'm trying to check if my array's dates have certain symbols in them e.g. "2019" or "-11-". I need to see if the array[i] doesn't have a date to add the inputted date to that slot. I could use !== undefined or isNaN, but it gives a number or empty as an error for some reason...

I've tried many different approaches, but I feel like this could be the way to go. Unless someone else figures out a better solution that is :D

Thanks for your time ^_^ Hopefully this is an easy fix that I just didn't notice!

/* 
date = user-inputted date (XXXX-XX-XX)
dateData = {name, dates} in database ("name", "XXXX-XX-XX")
newOrder[] = dateData.dates, but rearranged to a correct order, no date 
in the spot where "date" should be added 
*/

let newOrder = [dateData.length + 1];

for (let i = 0; i < newOrder.length; i++) {
  if (newOrder[i] /*solution here*/) {
    newOrder[i] = moment(date).format("YYYY-MM-DD");
    break;
  }
}

// after this I'll update the database with async

Solution

  • When using moment, you could use the moment#isValid method to check if the current value is a valid date.

    Although, I don't find it really clear what you are trying to achieve. Perhaps you can update your example with some data.

    let newOrder = [dateData.length + 1];
    
    for (let i = 0; i < newOrder.length; i++) {
      const parsedDate = moment(date);
    
      if (newOrder[i] && parsedDate.isValid()) {
        newOrder[i] = parsedDate.format("YYYY-MM-DD");
        break;
      }
    }