11

For example if the number 752 contains the number 5? Whats the best way to check? Convert to string or divide into individual digits?

user3312156
  • 153
  • 1
  • 1
  • 8

5 Answers5

20

Convert to string and use indexOf

(752+'').indexOf('5') > -1

console.log((752+'').indexOf('5') > -1);
console.log((752+'').indexOf('9') > -1);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • 2
    The `.` operator has higher precedence than `+`, so you need parentheses for this to really work. – Pointy Jul 29 '15 at 14:22
  • 2
    You have a problem in your operator precedence. It should be `(752+'').indexOf('5')`, otherwise `''.indexOf('5')` will evaluate first. – BoppreH Jul 29 '15 at 14:22
  • 2
    A Regex would also be an order of magnitude less efficent @Nick – Liam Jul 29 '15 at 14:23
3

Convert to string and use one of these options:

indexOf():

(number + '').indexOf(needle) > -1;

includes():

(number + '').includes(needle);
Halfacht
  • 924
  • 1
  • 12
  • 22
1

You can use 3 ways:

  1. Check it by string contains:

    var num = 752;
    num.toString().indexOf('5') > -1 //return true or false - contains or not
    
  2. Check by loop

    var f = 2;
    while(num > 0 ){
      if( num % 10 == f){
        console.log("true");
        break;
      }
      num = Math.floor(num / 10); 
    }
    
  3. Check by regular expressions

     num.toString().match(/5/) != null //return true if contains
    
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
RAZVOR
  • 55
  • 1
  • 7
0

function checkNumberIfContainsKey(number, key){
    while(number > 0){
        if(number%10 == key){
            return true;
        }
        number = Math.trunc(number / 10);        
    }
    return false;
}
console.log(
  checkNumberIfContainsKey(19, 9),   //true
  checkNumberIfContainsKey(191, 9),  //true
  checkNumberIfContainsKey(912, 9),  //true
  checkNumberIfContainsKey(185, 9)  //false
);

The most efficient solution among available answers because of the complexity of this program is just O(number of digits) if number = 10235 then the number of digits = 5

Vhndaree
  • 594
  • 1
  • 6
  • 20
0

You can also use "some" function. "Some"thing like this:

    function hasFive(num){
         return num.toString().split("").some(function(item){
          return item === "5";
         }); 
    }

and then you can call it:

   hasFive(752)

Further improved is that you make a function that takes number and digit you want to check:

       function hasNumber(num, digit){
             return num.toString().split("").some(function(item){
                 return item == digit;
             }); 
        }

And then call it in similar way:

hasNumber(1234,3) //true
hasNumber(1244,3) //false

So that way we can check any number for any digit. I hope so "some"one will find this useful. :)