Finding Number in String

Hello.

I am trying to return true if there is a number within the string and false if there are none, but I think I am getting confused with how my conditional equates (possibly due to some automatic type conversion).

I am only splitting the string into a character array as my attempt to compare numbers with charAt() also failed.

I DO NOT want to use regex.

Thank you :slight_smile:

function findTicketPrices (emailString) {
  let splitString = emailString.split("")
  for (let i = 0; i < splitString.length; i++) {
    for (let j = 0; j < 10; j++) {
      if (j == splitString[i]) {
        return true;
      }
    }
  }
  return false;
}

Loop through the string, if a character parses as a number, return true. Otherwise there arenโ€™t any numbers, return false. You donโ€™t need to split the string or anything, you can just loop through the characters. Eg

for (let char of emailString) {
  const possibleNum = parseInt(char);
  if (!Number.isNaN(possibleNum)) return true;
}
return false;

Edit: sorry, forgot zero is a number, edited example

Or can check the char code, eg

const code = char.charCodeAt();
if (code >= 48 && code <= 57) return true;

Edit again:

Or can check the result of parseInt-ing is a number >= 0, that also works (NaN is the only other response and will return false):

if (parseInt(char) >= 0) return true

Regex is much simpler here, why do you not want to use it?

2 Likes

Wow. Thanks for so much attention!

I am avoiding regex as I am preparing for an exam whereby I will have to explain my understanding of certain JS code. I think regex, due to being more simple, would avoid some of the things I am to cover.

Thank you so much for your carful responses :slight_smile:

1 Like