Regular Expression Javascript binary number validation
i am trying to convert binary to decimal value
I am need a regular expression for validating the binary number.
//for now i am using
var binary="1234"
/^-{0,1}\d+$/g.test(binary)
//my output:
1
but i want the output to say not in binary for开发者_Go百科mat.
Thanks in advance
/^-{0,1}\d+$/g.test(binary)
validates any positive or negative integer (\d
means "any digit"; also -{0,1}
can be written as -?
). The g
global flag doesn't make much sense here since you want to validate an entire string, not a substring in a longer, multi-line string (which wouldn't work anyway because the anchors ^
and $
make sure of that already).
Try this instead:
/^[01]+$/.test(binary)
That it matches every found entry and not just the first.
/[^0-1]/g.test(binary)
In this way checks all characters that aren't 0 or 1.
Probably isn't the best way to do it, but it worked for me.
精彩评论