简体   繁体   中英

How to check if entire string matches regular expression in Javascript?

Is there a function in javascript which checks if entire string matches some regular expression

'00'.match(/^0|([1-9][0-9]*)$/g) for example returns ['0']

I know I can simply check if the matched part is equal to the string, but I'm just curious if such function already exists

edit:

'01'.match(/^0|1$/g) returns ['0', '1'] and '01'.match(/^(0|1)$/g) returns null as expected.

I though | has precedence over ^ or $. Can someone explain what /^0|1$/g actually matches?

I don't know what you exacty want to achieve. I suppose you want to match eiter zero or a number, not beginning with zero. Then try this:

'00'.match(/^(0|[1-9][0-9]*)$/g)

This does not match '00', but all the other cases.

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