Dainius Vaičiulis
Dainius Vaičiulis

Reputation: 502

Javascript: How to check if two numbers exist in string? (regex)

I have this string :

testString = "child 4 to 10 years old";

How to check if the string contains two (or more) numbers?

testString.match("??")

Thanks!

Upvotes: 1

Views: 1664

Answers (3)

Ilya Ilin
Ilya Ilin

Reputation: 2401

"String0With1Some2Words3And4Integers0000".split('').reduce((val, acc) => (
    val  + (parseInt(acc) ? 1 : 0))
, 0)

Upvotes: 0

endy
endy

Reputation: 3872

   if (testString.match(/(\d+)/).length >= 2) {

Is a very simple/readable solution.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

This would find a match if the string contains atleast two numbers.

testString.match(/(?:.*?\b\d+\b){2}/)

or

/(?:.*?\b\d+\b){2}/.test(str);

or

If you also want to deal with decimal numbers then try this,

/(?:.*?\b\d+(?:\.\d+)?\b){2}/.test(str);

Upvotes: 3

Related Questions