0

I have some Single line of text fields in my Application which store data in this format(3 years, 4 Months and 4 days) something like that. Now I want to retrieve just the integer part from the fields and want to give in if condition to check some criteria.

Can anyone help me how to achieve this?

Pollyanna
  • 89
  • 1
  • 2
  • 6
  • 1
    You can do this with regex, but you will have to supply some sample code to test – Vince Nov 07 '19 at 11:10
  • here you can find the answer for your question: https://stackoverflow.com/questions/10003683/extract-get-a-number-from-a-string , answered long time ago – Zerhogi Nov 07 '19 at 12:07
  • 2
    Possible duplicate of [Extract ("get") a number from a string](https://stackoverflow.com/questions/10003683/extract-get-a-number-from-a-string) – Zerhogi Nov 07 '19 at 12:09

1 Answers1

0

Assuming the format you provided us is exact then you can try something like this.

let exampleString = "3 years, 4 Months and 4 days";

const extractYMD = (input) => {
  const stringArray = input.split(' ');
  //split the string on every space
  //it will create an array that looks like this
  //["3", "years,", "4", "Months", "and", "4", "days"]
  //then you can use the index to find your ints
  const years = parseInt(stringArray[0])
  const months = parseInt(stringArray[2])
  const days = parseInt(stringArray[5])
  //using parseInt because values inside the array are still strings
  //don't need to assign to variables but did it for clarity

  if(years <= 3){
   console.log('example condition')
   //do something here
  }
  
  console.log(years, months, days)
  //logging to console so you can see output
  
 return [years, months, days];
  // return the values if you need them for something
};

extractYMD(exampleString);

Using regex as others have suggested is also an option but there is a risk you will get an output like 324 and you won't know if its 32 years and 4 days or 3 months and 24 days. You can learn about and test regex here.

Keep in mind that the function above is very dependent on the format being exactly how you described. Any deviation will cause problems. Ideally you should seek to retrieve the data before it gets converted to this string format. But we need to see more of your code to understand why you're in this situation.

Thomas Ham
  • 70
  • 2
  • 6