Check if a Given String is Binary String or Not in JavaScript
Last Updated :
05 Jul, 2024
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:
Approach 1: Using Regular Expression
Regular expressions are patterns used to match character combinations in strings. In this approach, we use a regular expression pattern that matches strings containing only '0's and '1's. If the string matches this pattern, it is a binary string.
Example: This example shows the implementation of the above-explained approach.
JavaScript
function isBinaryString(str) {
// Regular expression pattern to match
// only 0s and 1s
const binaryPattern = /^[01]+$/;
// Test if the string matches the pattern
return binaryPattern.test(str);
}
console.log(isBinaryString("101010"));
console.log(isBinaryString("10102"));
Approach 2: Using Loop through characters
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"));
Approach 3: Using parseInt()
Another approach is to use the parseInt() function in JavaScript. We try to convert the string into a number using parseInt(). If the string represents a binary number, parseInt() will successfully convert it into a number. We then compare this number with the original string. If they match, it means the string is a binary string.
Example: This example shows the implementation of the above-explained approach.
JavaScript
function isBinaryString(str) {
// Try to convert the string into
// a number using parseInt()
const num = parseInt(str, 2);
// Compare the converted number
// with the original string
return num.toString(2) === str;
}
console.log(isBinaryString("101010"));
console.log(isBinaryString("10102"));
Approach 4: Using every() method
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"));
Using Set to Check if a Given String is Binary String or Not
In this approach, we create a set from the characters of the input string and then check if the set contains only the characters '0' and '1'. If the set contains any other characters, we conclude that the string is not a binary string.
Example:
JavaScript
function isBinaryStringUsingSet(str) {
// Create a set from the characters of the string
const charSet = new Set(str);
// Check if the set contains only '0' and '1'
for (let char of charSet) {
if (char !== '0' && char !== '1') {
return false;
}
}
return true;
}
console.log(isBinaryStringUsingSet("101010")); // Output: true
console.log(isBinaryStringUsingSet("10102")); // Output: false
Similar Reads
Check if a given String is Binary String or Not using PHP Given a String, the task is to check whether the given string is a binary string or not in PHP. A binary string is a string that should only contain the '0' and '1' characters. Examples:Input: str = "10111001"Output: The string is binary.Input: str = "123456"Output: The string is not binary.Table of
5 min read
Check if the ith Bit is Set or Not using JavaScript Checking if the ith bit is set or not in a binary representation is a common task in programming, especially in scenarios where bitwise operations are utilized. In this article, we'll explore multiple approaches to accomplish this using JavaScript. Given a non-negative integer num and an index i, we
2 min read
Check two given strings are isomorphic in JavaScript Two strings are said to be isomorphic if it is possible to map every character of the first string to every character of the second string. Basically, in isomorphic strings, there is a one-to-one mapping between every character of the first string to every character of the second string. We can also
5 min read
How to check a string data type is present in array using JavaScript ? In JavaScript, an array is a collection of data that can be of the same or different type. If we have the array containing the data, our task is to identify if it is a string data type. In this article, we will learn how to use the typeof operator. Syntax: typeof value Note: The typeof operator retu
3 min read
Check if a variable is a string using JavaScript Checking if a variable is a string in JavaScript is a common task to ensure that the data type of a variable is what you expect. This is particularly important when handling user inputs or working with dynamic data, where type validation helps prevent errors and ensures reliable code execution.Below
3 min read
How to Check if a Variable is an Array in JavaScript? To check if a variable is an array, we can use the JavaScript isArray() method. It is a very basic method to check a variable is an array or not. Checking if a variable is an array in JavaScript is essential for accurately handling data, as arrays have unique behaviors and methods. Using JavaScript
2 min read
Check if two strings are permutation of each other in JavaScript In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: Tr
4 min read
Check if Strings are Equal in JavaScript These are the following ways to check for string equality in JavaScript:1. Using strict equality operator - Mostly UsedThis operator checks for both value and type equality. it can be also called as strictly equal and is recommended to use it mostly instead of double equals.JavaScriptlet s1 = 'abc';
2 min read
How to check the given string is palindrome using JavaScript ? A palindrome is a word, sentence, or even number that reads the same from the back and from the front. Therefore if we take the input, reverse the string and check if the reversed string and the original string are equal, it means the string is a palindrome, otherwise, it is not. Approach: When the
3 min read
How to Get the Length of a String in Bytes in JavaScript ? In JavaScript, determining the length of a string in characters is straightforward using the length property. However, in many cases, particularly when dealing with file sizes, network protocols, or database storage, you might need to know the length of a string in bytes. This is because characters
3 min read