简体   繁体   中英

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?

* 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]+/

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.

这是写数字正则表达式的正确形式:

 \d+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM