简体   繁体   中英

Test if string contains only characters

The goal is to compose a regex using the.test() or.match() to check if a string contains all numbers.

For example:

  1. str "10001" should return true
  2. str "1ab001" should return false

So far my regex looks like this:

str.match("^[0-9]*$")

I'm getting null returned

I am also looking for ways to do this using the.test() method which will return true or false.

Any help with working with regex is greatly appreciated.

Your regexp is correct. Using regexp literal you will be able to use test:

/^[0-9]*$/.test('10001')
-> true

/^[0-9]*$/.test('10ab001')
-> false

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