Filtering out the Characters?

So I want to do something like this to remove the ‘foo’ from the string
not sure whats up with it?

function random (arr)
{
  var arr1 = arr.split('')
  console.log(arr1)
  var arr2 = []
 for(var x = 1 ; x<arr1.length ; x++)
    {
      if ( arr[x] === /[0-9]/)
      { 
        arr2.push(arr[x]);
        
      }
    }
 

  console.log(arr2)

}

random("07506189foo")


Your parameter accepts a string input, check the input if it’s a number or a string first before storing.


    */
    var arr1 = num.split('')
    console.log(arr1)
    var arr2 = []
    
    for(var x = 1 ; x<arr1.length ; x++)
    {
      arr1[x] === String(arr1[x])
      console.log(arr1[x])
       console.log(typeof arr1[x])
      if ( arr1[x] === /[0-9]/)
      { 
        arr2.push(arr1[x]);
        
      }
    }
    console.log(arr2)

image

In this line you’re strictly comparing the contents of an array index (which in your example contains either a number or a string) against a regular expression (which is an object*). This is always going to return false because numbers and strings aren’t objects.

Instead of directly comparing against your regular expression you should use RegExp.prototype.test

For example:

/[0-9]/.test("a")
// returns false

/[0-9]/.test(1)
// returns true

*When you strictly compare objects in javascript, it doesn’t check if both sides have the same value – it checks whether they both refer to the same thing

I got this function to work by itself but when I put it into a larger function it doesn’t work?

function validMobileNumber (num) {

    var arr1 = num.split('')
    console.log(arr1)
    var arr2 = []
    
    for(var x = 0 ; x<arr1.length ; x++)
    {
      arr1[x] === String(arr1[x])
      console.log(arr1[x])
       console.log(typeof arr1[x])
      if (/[0-9]/.test(arr1[x]))
      { 
        arr2.push(arr1[x]);
        
      }
    }
    console.log(arr2)
    num=arr2.join(' ')

    console.log(typeof num)


    function refere (num)
    {
   
      if((num.slice(0,2)==='07' && (num.slice(2,num.length).length) === 9) || (num.slice(0,4)==='+447' && (num.slice(4,num.length).length) === 9)||(num.slice(0,5)==='00447' && (num.slice(5,num.length).length) === 9))
     {
       return true;
      }
     return false;
    }
   
   return refere(num)
  }

  validMobileNumber("07506172506")

By itself the same code of the refere() function seems to work fine

  
   function refere (num)
  {
   
    if((num.slice(0,2)==='07' && (num.slice(2,num.length).length) === 9) || (num.slice(0,4)==='+447' && (num.slice(4,num.length).length) === 9)||(num.slice(0,5)==='00447' && (num.slice(5,num.length).length) === 9))
    {
      return true;
    }
    return false;
  }


  refere("07506172506")