Check if a string is only composed of 0

8

I want to check if for example a string "00000000" is only zeros and give true, however a "0000a0e0b" is false, why I tried with! isNaN and gives true having at least 1 number

var palavra = 00000;
var palavra2 = a00a0;
if(!isNaN(palavra)) // Aqui é pra dar true
if(!isNaN(palavra2)) // Aqui era pra dar false, mas dá true
    
asked by anonymous 17.06.2018 / 23:13

4 answers

7

If you are testing strings, an alternative is to use regular expressions:

var palavra = "00000";
var palavra2 = "a00a0";

console.log(/^0+$/.test(palavra)); // true
console.log(/^0+$/.test(palavra2)); // false
  • ^ indicates the beginning of the string
  • 0+ indicates one or more occurrences of 0
  • $ indicates end of string

That is, the expression /^0+$/ corresponds to a string with one or more occurrences of 0 , from beginning to end.

The test method checks if the last string matches the expression.

    
17.06.2018 / 23:22
4
  

As my previous response was identical to that of @hkotsubo and we posted at exactly the same time, I'll leave a variant for reference.

You can also use a regular negation expression:

[^0]

The ^ (negated set) or "set denied" sign will check if the string has any other character that is not 0 . If you find it, you do not just have 0 . To reverse the check, you can use the ! sign. In this case, true will indicate that it only has 0 .

Example:

var palavra = "00000000";
var palavra2 = "0000a0e0b";

console.log(!/[^0]/.test(palavra)); // retorna true, só contém 0
console.log(!/[^0]/.test(palavra2)); // retorna false, não tem só 0 ou nem tem 0
    
17.06.2018 / 23:22
4

I'd force a number conversion with + , then check if 0 was given. It's quite simple:

var palavra = '00000';
var palavra2 = 'a00a0';
console.log(+palavra === 0);
console.log(+palavra2 === 0);

Only one however: if the string is 0b00000 (with any number of zeros after b ), it can be interpreted as a binary string of value 0 ( support depends of the browser), and the result of the comparison will give true .

    
18.06.2018 / 03:32
3

Since you already have answers with regular expressions, I show you an alternative with no regular expressions, although it is not so compact.

The idea is to test with another string constructed with zeros, for the same amount of letters, at the expense of the method repeat string. This repeat will repeat a zero multiple times until it has the corresponding size.

Example:

var palavra = "00000000";
var palavra2 = "0000a0e0b";

console.log(palavra === "0".repeat(palavra.length));
console.log(palavra2 === "0".repeat(palavra2.length)); 
    
18.06.2018 / 03:14