简体   繁体   中英

Function to extract numbers only from a string

I have written a function that I want to take in a string and then return a string that contains only the number characters from the original string. It

function pureNumbers() {
      var result;
      for (var i = 0; i < phoneNumber.length; i++) {
         if (Number(phoneNumber[i]) !== NaN) {
            result ? result = result + phoneNumber[i] : result = phoneNumber[i]
         }
      }
      return result;
   }

pureNumbers('(123) 456-7890')

Desired result:

result: '1234567890'

What I actually get is:

result: 'undefined(123) 456-7890'

I know there's two issues here (possibly more).

  1. The undefined at the beginning of my result is because my function is attempting to return the value of result in the first loop's iteration, before anything has been assigned to it. I set up the ternary conditional to cover this, not sure why it's not working...
  2. My first if() conditional is intended to make the given character of the string be added to result only if it is a number , yet every single character is being added.

Any help appreciated - thanks in advance.

This gets all the numbers from a string as an array, then .join("") to join together the strings with no delimiter between them, Ie, a consecutive concatenation string of digit matches.

var numberPattern = /\d+/g;

'something102asdfkj1948948'.match( numberPattern ).join("");

Yields "1021948948"

The basic logic is below:

var x = 'Hello please call (727) 902-1112';

var numbers = x.match(/[0-9]/g).join('');

console.log(numbers);

Result: 7279021112

Now as to a function, I think this might help you:

var x = 'Hello please call';
var y = 'Hello please call (727) 902-1112';

    function pureNumbers(param) {
        result =  param.match(/[0-9]/g);

        if (Array.isArray(result)) {
            return result.join('');
        }
        return false;
    }

console.log(pureNumbers(x)); // returns false
console.log(pureNumbers(y)); // returns 7279021112

Note: isArray() does not work in older versions of IE 9. You would have to do it differently .

Your can also try the following: string.replace(/[^0-9]/g, ''); OR string.replace(/\\D/g,''); to strip all the non-digit characters.

function pureNumbers(str) { 
    var num = str.replace(/[^0-9]/g, ''); 
    return num; 
}

alert(pureNumbers('(123) 456-7890'));

I only changed your function a little bit, though it can be solved in many ways, especially with regex.

function pureNumbers(phoneNumber) {
  var result = "";
  for (var i = 0; i < phoneNumber.length; i++) {
     if (!isNaN(phoneNumber[i]) && phoneNumber[i].trim() !== '') {
        result += phoneNumber[i];
     }
  }
  return result;
}

Hope you may get some hint and improve for better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM