How to useevery() method in Javascript
The every() method tests whether all elements in the array pass the test implemented by the provided function. In this approach, we split the string into an array of characters and use the every() method to check if every character is either ‘0’ or ‘1’.
Example: This example shows the implementation of the above-explained approach.
Javascript
function isBinaryString(str) { return str.split( '' ).every(char => char === '0' || char === '1' ); } console.log(isBinaryString( "101010" )); console.log(isBinaryString( "110011" )); console.log(isBinaryString( "12345" )); |
true true false
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it’s every character present in the string.
Example:
Input: "101010"
Output: True, binary string
Input: "110211"
Output: Falee,
Explanation: This input has "2" in string and that is not a binary number.
These are the following approaches:
Table of Content
- Using Regular Expression
- Using Loop through characters
- Using parseInt()
- Using every() method