Allen F Allen F - 2 years ago 82
Javascript Question

How to strip non integers in array elements in JavaScript

I'm quite new to programming, and I feel that similar questions have been asked before. But I've tried to apply them and know I am missing something fundamental.

Given an array:

var myArray = [24.203, 12*45, 000-1, 4567+00];

I'd like to strip all non integers, so that I have something like this:

var myArray = [24203, 1245, 0001, 456700];

I know of the .replace method, but I can't seem to get it work. Here are four things I've tried:

function stripNonIntegers(arr) {
var x;
this.myArray = myArray;
for(x = 0; x < 10; x++) {
myArray[x] = myArray[x].replace(/\D/g, '');
} }

This returns an error saying myArray is undefined.

var x;(myArray); { //I don't like the semicolons but I get an error if I omit them
for(x = 0; x < 10; x++)
{myArray[x] = myArray[x].replace(/\D/g, '');
} }

this returns an error saying x is undefined.

stripNonIntegers= function(arr) {
for (x =0; x<this.length; x++)

This output is undefined.

var stripNonIntegers= myArray[x]; {
for (x=0; x<myArray.length; x++) {
stripNonIntegers = myArray.replace(/[^\d]/g, '');
} }

And this one also says x is undefined. This post explains how to use the .replace method with a regex of /D to strip non-numerics from a string, but I can't seem to get it to work with an array (not a function). Thus I try to stick a 'for' loop in there so it treats each element as its own string. I know I'm making a stupid mistake, but for all my trying, I can't identify it. I'm shooting in the dark.

Any tips? Thanks in advance.

Answer Source
var myArray = ['24.203', '12*45', '000-1', '4567+00'];

var myNewArray = {
    return parseInt(value.replace(/\D/g,''), 10);

\D is a shorthand character class that matches all non-digits.

The above code works when your array elements are strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download