JavaScript binary to decimal application (Part Two): Regular Expressions

Continuing on from the previous post, where I set up a pen on codepen.io to create a simple application that would take a binary number and covert to decimal. I’d laid out front end and the two tasks I had left were:

  • logic for the binary to decimal conversion.
  • restricting the entry value to 1’s and 0’s, probably using regular expression.

Filtering binary values using Regex

The one currently on my to do list is limit only binary values being entered into the input field. First hurdle was being able to compare the value input. Regex was my go to choice and was simple enough:

/[10]/g  -- pretty much translates to a range of digits from 1 to 0

However, there were a range of issues:

  • I assumed that even though the expression would find all instances of the pattern, it wasn’t working properly and I would have to create code to iterate through each character in the input [turned out I was using the wrong regex object methods i.e. match instead of test]
  • After finding the right method call ‘regex.test()’ the condition was picking some input which wasn’t binary.

My condition was

if (value contains 1 or 0) {
     /* code to execute if input is binary */
} else {
    /* code to execute if input isn't binary */
}

Any values which contained either a ‘1’ or ‘0’ would be accurately considered as binary figures. However, the issue was when a non valid input contained either of the valid elements ‘1’ or ‘0’ e.g. 10A, that would be considered binary as well.

I’d searched for numerous forums tips on pattern matching what was needed and excluding others i.e. show me only cases where it’s 1’s and 0’s and excluded everything else. Pretty sure there are ways but none that I could find.

Solution

The solution was very simple however, by seeking a pattern that considered everything except 1’s and 0’s and then using that as the filter to discount all non valid binary  input meant that the remaining items would surely be binary values.

if (value does not contain 1 or 0){  
  /* code to execute if not binary */
} else {
  /* code to execute if input is binary */
}

See the Pen xELLJP by Donal D’silva (@donyd) on CodePen.

Closing thoughts

The task was deceptively simple, even though it proved somewhat daunting in the beginning. Further excursions into Regex is warranted, just to get beyond the basic pattern matching that can be done. So with that we’re one step closer to the end goal.