Check if a number starts with another number or not js

How to Check if a Number Starts with Another Number in JS

If you want to check whether a number starts with another number or not in JavaScript, you can do it using the toString() method and the startsWith() method. Here is how:

Method 1: Using toString() and startsWith()


let mainNumber = 12345;
let subNumber = 12;

if(mainNumber.toString().startsWith(subNumber.toString())) {
    console.log("Main number starts with sub number");
} else {
    console.log("Main number does not start with sub number");
}

In this method, we first convert both the main number and sub number to strings using the toString() method. Then we use the startsWith() method to check if the main number starts with the sub number.

Method 2: Using substr()


let mainNumber = 12345;
let subNumber = 12;

if(mainNumber.toString().substr(0, subNumber.toString().length) === subNumber.toString()) {
    console.log("Main number starts with sub number");
} else {
    console.log("Main number does not start with sub number");
}

In this method, we use the substr() method to extract the first few characters of the main number that are equal to the length of the sub number. Then we compare this extracted string with the sub number using the strict equality operator (===).

Both of these methods can be used to check if a number starts with another number in JavaScript. You can choose the method that you find easier to understand and implement.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe