Replace String in Javascript Array

Replace String in Javascript Array

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?

3

5 Answers

Yes.

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

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

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 can also do it inline in a shorter syntax

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

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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.