Search code examples
javascriptregexstring-formattingnumber-formatting

How do I extract numbers from a comma-separated sequence using a regex?


I have the following string as an example:

var str = "3,000, 2000, 1,000"

and I want to extract 3000, 2000, 1000 using regex str.match(/\d+/g) but the result is wrong:

['3', '000', '2000', '1', '000']

How do I fix this?


Solution

  • My Answer:

    const str = "3,000, 2000, 1,000"
    const patt = /(\d+(\,)?)+\d*/g;
    const res = (str.match(patt)).map(ele=> +ele.replace(/\,/g, ""))
    console.log(res)