Count integers from a string in JavaScript

Today’s problem is quite simple, we need to find total numbers from a user input.

Example 1:

Input string: I’m Sunil and 25 years old. I’ve 5.6 years of experience and will be 6 years of experienced in year 2017.

Output: 5

Explanation: 25 will be out first number. Then we have 5.6, in this case we’ll consider it two numbers (this is requirement), but if it is like 56 then this will be 1 number. So by now we have 3 numbers. Fourth one will be 6, and fifth will be 2017.

Example 2:

Input string: +45.6 – 89

Output: 3 (45, 6, 89)


Step 1: First of all check for boundary conditions like invalid input; In my code I might not handled all.

Step 2: If input string is good, then add a special character at the end of the string. In my case I have added period (.).

Step 3: Loop and read all the characters of the string one by one.

Step 4: If character is an integer then add it in a variable. If character is not an integer and previously defined variable is not empty that means we have found an integer and current character is a non integer, we need to skip this. So reset the variable that is holding integers and increase the variable that is counting the number of integers.


<!DOCTYPE html>
    <meta charset="UTF-8">
    <title>Find integer count from a string</title>
    <script type="text/javascript">
        function FindNumbers()
            var someString = document.getElementById('txtInput').value;
            var totalNumbersInString = 0, finalString = '';
            someString += '.';
            for (var i = 0; i < someString.length; ++i)
                if (isNaN(someString[i]) && finalString.length > 0) {
                    finalString = '';
                else if(!isNaN(someString[i])) {
                    finalString += someString[i];

          document.getElementById('lblOutput').innerHTML = totalNumbersInString;
    Input string: <input id="txtInput" type="text"> <br>
    <input value="Process" onclick="FindNumbers()" type="submit"><br>
    Output: <div><label id="lblOutput"></label></div>





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s