Search code examples
javascriptstringnumbersextract

Extracting a Numbers from a String in JavaScript


I'd like to extract the numbers from the string. (E.g. I want the 24 and 380 from the string 24:380) I'd like to assign it in respective variables. Is there any way I could do that?

I couldn't find any solution to this problem.


Solution

  • You can use RegEx:

    const paragraph = 'The quick brown 45 jumps over the lazy 23:12. It barked.';
    const regex = /(\d+)/g;
    const found = paragraph.match(regex);
    
    console.log(found);
    // expected output: Array ["45", "23", "12"]