-1

I believe very similar questions were asked, however, the provided answers/examples are not really applicable to my question. Well, at least not to the extent of my knowledge - I'm not a Javascript connoisseur, so pardon me for that.

Working with a Google Home device, I have the user say how much time he would like to have breakfast. He can answer in minutes, which is saved into a variable the_breakfast_minutes. How can I then extract the number from, for example, these strings using JS:

  • 20 minutes
  • 5 minutes

etc.

Gladly appreciate your help!

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Velionis
  • 17
  • 5

2 Answers2

2

First, you can get the number as a string like this:

minutes_string = the_breakfast_minutes.split(" ")[0]

Then, you can convert it to a number (if you need to) like this:

minutes_number = parseInt(minutes_string)

Here's a snippet with a working example:

const the_breakfast_minutes = "20 minutes"
const minutes_string = the_breakfast_minutes.split(" ")[0]
const minutes_number = parseInt(minutes_string)

console.log(minutes_number)
Alejandro De Cicco
  • 1,216
  • 3
  • 17
1

Answering the question generally: you can use match(regular expression).

const str = "minu20tes"
const number = parseInt(str.match(/\d+/)[0])

That is assuming the number to extract is a positive integer. If needed, /[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?/ will also include negative, decimals and exponents.

Moon Moon
  • 59
  • 3