44

I have an array in javascript. This array has strings that contains commas (","). I want all commas to be removed from this array. Can this be done?

2
  • Can't you filter the strings before them being pushed in the array? Otherwise is just a simple for loop. Commented Jun 4, 2009 at 21:52
  • I tried to but the strings are coming from other place, dynamically. But it doesn't matter anyway, I figured out what I was doing wrong. I was leaving a comma after every db result. I was convinced that the array push I was doing was adding a comma after every push. I'm a starter in JS. Thanks anyway. Commented Jun 4, 2009 at 22:05

5 Answers 5

63

Yes.

for(var i=0; i < arr.length; i++) {
 arr[i] = arr[i].replace(/,/g, '');
}

2 Comments

+1 for getting closer than me but you need to do something with the result, replace does not mutate the string.
Sorry kekoav, Shoudn't it be: arr[i] = arr[i].replace(/,/g, ''); ??
40

The best way nowadays is to use the map() function in this way:

var resultArr = arr.map(function(x){return x.replace(/,/g, '');});

this is ECMA-262 standard. If you nee it for earlier version you can add this piece of code in your project:

if (!Array.prototype.map)
{
    Array.prototype.map = function(fun /*, thisp*/)
    {
        var len = this.length;
        if (typeof fun != "function")
          throw new TypeError();

        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
            if (i in this)
                res[i] = fun.call(thisp, this[i], i, this);
        }

        return res;
    };
}

Comments

16

you can also do it inline in a shorter syntax

array = array.map(x => x.replace(/,/g,""));

Comments

9

You can simply do:

array = ["erf,","erfeer,rf","erfer"];
array = array.map(function(x){ return x.replace(/,/g,"") });

Now Array Becomes:

["erf", "erfeerrf", "erfer"]

1 Comment

You do not need to (read: should not) test the regex yourself, that happens under the hood anyway.
0

Sure -- just iterate through the array and do a standard removal on each iteration.

Or if the nature of your array permits, you could first convert the array to a string, take out the commas, then convert back into an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.