Search code examples
javascripttimedialogflow-esgoogle-home

Extracting a number from a string using Javascript


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!


Solution

  • 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)