designeng
designeng

Reputation: 39

How to test if a string contains a number with regular expression in javascript?

I'm trying with

function hasANumber(value) {
    return /^.*[0-9]*.*$/.test(value);
}

Where I was wrong?

Upvotes: 1

Views: 1004

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174696

Just \d would be enough for this case.

> /\d/.test('foo')
false
> /\d/.test('fo1o')
true

[0-9]* in your regex matches a digit zero or more times, so it would allow also the strings which won't have a digit.

Upvotes: 1

Enrique Quero
Enrique Quero

Reputation: 612

This is the correct form to write the number regex is :

 \d+$

Upvotes: 0

Ortiga
Ortiga

Reputation: 8814

* in regex means zero or more

You should have used + which means one or more, as in:

/^.*[0-9]+.*$/

Although this can be simplified to:

/[0-9]+/

Upvotes: 1

Related Questions