41

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. 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. 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
  • 1
    +1 for getting closer than me but you need to do something with the result, replace does not mutate the string. Jun 4, 2009 at 21:58
  • 1
    Sorry kekoav, Shoudn't it be: arr[i] = arr[i].replace(/,/g, ''); ??
    – tekBlues
    Jun 4, 2009 at 21:59
37

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;
    };
}
13

you can also do it inline in a shorter syntax

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

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
  • You do not need to (read: should not) test the regex yourself, that happens under the hood anyway. Dec 8, 2015 at 10:06
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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.