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?
To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.
Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character. in fact every occurence of the same string is ONE object.
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
Yes.
for(var i=0; i < arr.length; i++) { arr[i] = arr[i].replace(/,/g, ''); }
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; }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With