Ad

Find Specific Digit In A Input Field Number In Javascript

- 1 answer

I am working on a Binary2Decimal convertor app, where when the user enters other than 0s and 1s in input field, then while clicking on convert it should alert the user to enter valid binary number.

Below is my code:


const binary = document.querySelector('.decimalConvertor__binary--bin');
const decimal = document.querySelector('.decimalConvertor__decimal--dec');
const submit = document.querySelector('.decimalConvertor__submit--sub');

submit.addEventListener('click', e => {
  const bin = binary.value;
  if(bin !== '' && ' ') {
    if(bin.length <=8) {
      let dec = 0;

    for (let i = bin.length-1; i >=0; i--) {
      dec += parseInt(bin[i]) * Math.pow(2, bin.length - 1 - i);
    }
    decimal.value = dec
    }else {
      alert('enter less than 8 numbers')
    }
  }else {
    alert('Please enter valid binary number')
  } 
});
Ad

Answer

try this, it uses regex to test whether the string contains numbers other than 1 and 0, if it does, then it shows the alert to enter a valid binary number:

var re = new RegExp("([23456789])");

submit.addEventListener('click', e => {
  const bin = binary.value;
  if(bin && !re.test(bin)) {
    if(bin.length <=8) {
      let dec = 0;

    for (let i = bin.length-1; i >=0; i--) {
      dec += parseInt(bin[i]) * Math.pow(2, bin.length - 1 - i);
    }
    decimal.value = dec
    }else {
      alert('enter less than 8 numbers')
    }
  }else {
    alert('Please enter valid binary number')
  } 
});

Here's a website where you can create regexes and it'll show you their explanation: https://regexr.com/ . Enter the regex there for it's explanation!

Ad
source: stackoverflow.com
Ad