Binary is a binary numeral system in which everything is expressed as “0” and “1”. JavaScript is a world’s most loved and used scripting language by developers. In this article we will talk about how to check if string is binary using JavaScript.
Create a function
First step is to create a function in JavaScript to check whether a string is binary or not.
function checkString(str) {
let isBinary = false;
for (let i = 0; i < str.length; i++) {
if (str[i] == "0" || str[i] == "1") {
isBinary = true;
} else {
isBinary = false;
}
}
return isBinary;
}
Code explanation
Let’s create a function with name checkString
. In the function, loop through the characters of the provided string and check if character contains 0 and 1. If yes, the string is binary otherwise not.
Consume the function
The next step is to consume the checkString
function where you require it.
Call the function something like this-
const isBinary = checkString("01100100110010");
console.log(isBinary); // it will print true
const isBinary2 = checkString("1212221002214");
console.log(isBinary2); // it will print false as it is not a binary
Conclusion
In this article we learnt about how to check whether a string is binary or not using JavaScript.
You can write me up for any JavaScript query you have at my email address jimcute8879@gmail.com.