Replace string in javascript array

后端 未结 7 2155
萌比男神i
萌比男神i 2020-12-08 14:10

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?

相关标签:
7条回答
  • 2020-12-08 14:46

    Yes.

    for(var i=0; i < arr.length; i++) {
     arr[i] = arr[i].replace(/,/g, '');
    }
    
    0 讨论(0)
  • 2020-12-08 14:48

    you can also do in inline in a shorter syntax

    array = array.map(x => x.replace(/,/g,""));
    
    0 讨论(0)
  • 2020-12-08 14:55

    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);
        });
    });
    
    0 讨论(0)
  • 2020-12-08 15:03

    You can simply do:

    array = ["erf,","erfeer,rf","erfer"];
    array = array.map(function(x){ return x.replace(/,/g,"") });
    

    Now Array Becomes:

    ["erf", "erfeerrf", "erfer"]

    0 讨论(0)
  • 2020-12-08 15:04

    Given the required string in variable s :-

    var result = s.replace(/,/g, '');
    
    0 讨论(0)
  • 2020-12-08 15: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.

    0 讨论(0)
提交回复
热议问题