How to useLoop through characters in Javascript
This method involves checking each character of the string individually. We loop through each character and verify if it’s either ‘0’ or ‘1’. If we encounter any other character, we conclude that the string is not a binary string.
Example: This example shows the implementation of the above-explained approach.
Javascript
function isBinaryString(str) { // Loop through each character of the string for (let i = 0; i < str.length; i++) { // If any character is not // '0' or '1', return false if (str[i] !== '0' && str[i] !== '1' ) { return false ; } } // If all characters are // '0' or '1', return true return true ; } console.log(isBinaryString( "101010" )); console.log(isBinaryString( "10102" )); |
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