Check if a string is composed only of '0' and '1'

Asked

Viewed 145 times

3

I want to check, for example, if the string '01001011' is composed only of '0' and '1'.

I’m creating an html learning project to convert binaries to decimal, and I want to create a function that makes sure that the value typed in the input is a binary combination, otherwise the user will have to enter another value. After that, by pressing 'Enter' the conversion will be done.

<input type="text" id="b-input" onkeypress="convert()">
function convert() {
    const binary = document.getElementById('b-input').value;
    if (binary === '') return alert("Please, enter a binary number");
}
document.getElementById('b-input').onkeypress = function(e) {
    if (e.code == 'Enter') {
        convert();
    } 
}

For now I could only check if the string is empty, and create the function that converts by pressing 'Enter'.

  • 1

    You can use regular expression: ^[01]+$.

  • ...I am creating an html project to convert binaries to decimal... why? Javascript has the function parseInt(string, base) parses a string argument and returns an integer in the specified base. Ex: console.log(parseInt("01001011",2)); returns 75.

  • 1

    @Augustovasques, a learning project?

  • @Jeffersonquesado, it may be.... has a good chance. I’m withdrawing the closing vote.

5 answers

7


Well, I don’t have much experience with Javascript, but I believe that the simplest way to solve this would be to use regular expressions (Regex) to verify the value entered, as referred by Luiz Felipe. Ai, would only have to change the condition in the Convert function to:

function convert() {
  const binary = document.getElementById('b-input').value;
  if (/^[01]+$/.test(binary) === 0) return alert("Please, enter a binary number");
}

Edit: As mentioned by hkotsubo, the comparison should be made to check whether the value is true or false, and not to compare it to '0'. So you should try:

if (! /^[01]+$/.test(binary)) return alert("Please, enter a binary number");

Another more laborious way but also simple to understand, is to make a loop that checks if each character of the inserted string is "0" or "1". Normally, in this type of checks I prefer the value returned to be true or false, so I also changed the function for this purpose.

function check_str(str){
  for (var i=0; i<str.length; i++){
    if (str[i] !='0' || str.charAt[i] !='1'){
      return false;
    }
  }
  return true;
}


function convert() {
    const binary = document.getElementById('b-input').value;
    if (check_str(binary) === false) return alert("Please, enter a binary number");
}


document.getElementById('b-input').onkeypress = function(e) {
    if (e.code == 'Enter') {
        convert();
    } 
}

To search more about regular expressions, you can try the following link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

  • It is worth remembering that the method test returns true or false, so instead of comparing it to zero, it should just be if (! /^[01]+$/.test(binary)) { não é binário } - including, therefore the strict comparison (===) in this case always results in false (so much true === 0 how much false === 0 are false and therefore will never enter into that if)

  • Oops, true. I wrote false in the second option (I even mentioned that I prefer to use true or false) and forgot the first solution. Thank you for mentioning.

5

Just to add another alternative, it can also do with pure JS functions in a minimally direct way. You can transform into array with split, filter through 0’s and 1’s with filter and check if the size matches the input:

function isBinary(val){
  return val.split('').filter(x => x == "0" || x == "1").length == val.length;
}

See the example working:

function isBinary(val){
  return val.split('').filter(x => x == "0" || x == "1").length == val.length;
}

function convert() {
  const binary = document.getElementById('b-input').value;
  console.log(isBinary(binary));
}
<input type="text" id="b-input" onkeyup="convert()">

By this I do not mean that this solution is better than the others that already exist, but it is another way to solve the problem.

  • I find it more obvious to filter by x => x != "0" && x != "1" and then check if the size is 0. They are equivalent solutions, but for me it is more direct to the point of checking if it is invalid

  • 1

    @Jeffersonquesado This is the inverse of the logic I used, but as the name of the function is in the affirmative isBinary I chose to build logic in the positive. But it is a good criticism.

2

You can use the parseInt. He will return NaN if the input is not valid.

window.document.querySelector('input#b-input').addEventListener("input", function(e) {
    if (isNaN(parseInt(e.data, 2))) {
        alert("Please, enter a binary number");
        e.target.value = "";
        return 
     }
});
<input type="text" id="b-input">

1

1

You said you want "convert binaries to decimal" (and unless it’s for learning purposes, I would use parseInt, which although more direct, has some details to consider - detailed below).

Anyway, one way would be to actually check if the string has only zeros and ones, like one of the answers indicated.

Although, if the idea is to convert from binary to decimal, I would already do the validation during the conversion:

var result = document.querySelector('#result');
window.document.querySelector('input#b-input').addEventListener("input", function(e) {
    var decimal = 0;
    var s = e.target.value;
    for (var i = 0; i < s.length; i++) {
        var digito = parseInt(s[i]);
        if (digito == 1) {
            decimal += Math.pow(2, s.length - i - 1);
        } else if (digito != 0) { // se for NaN também cai aqui
            decimal = NaN;
            break; // não é zero nem 1, posso interromper o loop
        }
    }
    if (isNaN(decimal)) {
        result.innerText = 'Não foi digitado um número binário';
    } else {
        result.innerText = `${s} em decimal=${decimal}`;
    }
});
<form>
  <input type="text" id="b-input">
</form>
<p id='result'></p>

That is, if during the conversion I find something that is not zero or one, it gives error. Otherwise, it continues to convert.

If you do the validation first and then the conversion also works, of course, but then you would have to go through the string twice, which seems unnecessary to me.


Another answer suggested using parseInt, which is a more direct alternative (and as I have already said, is what I would recommend, unless your project is for learning purposes).

But there’s a detail, for parseInt does not accept only zeros and ones, see:

for (var s of ['-01', '   10', '10xyz'])
    console.log(`${s} = ${parseInt(s, 2)}`);

Note that the character is also accepted - (to indicate that the number is negative), and spaces at the beginning are ignored, as well as anything after the digits (so in the string 10xyz, all after the x is ignored). This behavior is described in documentation.

So, you have to decide what you want: only a string containing zeros and ones, or any string that can be converted from binary to decimal (according to Javascript rules, for example)? If you have spaces, will you ignore or fail? Etc...

It is worth remembering that negative numbers, as already seen above, must be represented with the minus sign in front. But there is also the possibility of representing such numbers using the complement of two (but then I believe I already escape a little of the scope of the question, but anyway it is something to consider, if I will implement the algorithm instead of using what already has ready).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.