Skip to content
the poor coder

Check if a number starts with another number or not js

Poor Man
Published
Reading time
1 min read
On this page

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()#

Text

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()#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC