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?
-
Can't you filter the strings before them being pushed in the array? Otherwise is just a simple for loop.– Ionuț G. StanJun 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.– Manny CalaveraJun 4, 2009 at 22:05
5 Answers
Yes.
for(var i=0; i < arr.length; i++) {
arr[i] = arr[i].replace(/,/g, '');
}
-
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
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 also do it inline in a shorter syntax
array = array.map(x => x.replace(/,/g,""));
You can simply do:
array = ["erf,","erfeer,rf","erfer"];
array = array.map(function(x){ return x.replace(/,/g,"") });
Now Array Becomes:
["erf", "erfeerrf", "erfer"]
-
You do not need to (read: should not) test the regex yourself, that happens under the hood anyway. Dec 8, 2015 at 10:06
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.