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?
Yes.
for(var i=0; i < arr.length; i++) {
arr[i] = arr[i].replace(/,/g, '');
}
you can also do in inline in a shorter syntax
array = array.map(x => x.replace(/,/g,""));
You can use array.map
or forEach
. According to our scenario, array.map
creates or given a new array. forEach
allows you to manipulate data in an already existing array. Today I used it like this for me.
document.addEventListener("DOMContentLoaded", () => {
// products service
const products = new Products();
// get producsts from API.
products
.getProducts()
.then(products => {
/*
raw output of data "SHEPPERD'S SALLAD" to "SHEPPERDS SALLAD"
so I want to get an output like this and just want the object
to affect the title proporties. other features should stay
the same as it came from the db.
*/
products.forEach(product => product.title = product.title.replace(/'/g,''));
Storage.saveProducts(products);
});
});
You can simply do:
array = ["erf,","erfeer,rf","erfer"];
array = array.map(function(x){ return x.replace(/,/g,"") });
Now Array Becomes:
["erf", "erfeerrf", "erfer"]
Given the required string in variable s :-
var result = s.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.