Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 830
Manny Calavera Avatar asked Jun 04 '09 21:06

Manny Calavera


People also ask

How do you replace values in an array?

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.

Can you change strings in JavaScript?

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.

How do you replace a letter in a string JavaScript?

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.


2 Answers

Yes.

for(var i=0; i < arr.length; i++) {  arr[i] = arr[i].replace(/,/g, ''); } 
like image 129
Kekoa Avatar answered Sep 18 '22 17:09

Kekoa


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;     }; } 
like image 44
Maurizio In denmark Avatar answered Sep 20 '22 17:09

Maurizio In denmark