How to change a specific value of a string in an array?

Asked

Viewed 130 times

0

I have an array:

let arr = ['Feijao, Arroz', 'Melancia', 'Banana', 'Laranja,Uva']

and would like her to become:

let arr = ['Feijao, Arroz', 'Melancia', 'Banana', 'Laranja, Uva']//(consertando o erro de vírgula).

I wrote the code

let arr = ['Feijao, Arroz', 'Melancia', 'Banana', 'Laranja,Uva']
for(let i = 0; i < arr.length; i++){
    let search = arr[i].search(/,\w/g)
    if(search >= 0){
        arr[i][search] += ' '
    }
    console.log(search);
}
console.log(arr)

But it doesn’t change anything at all. I’ve tried charAt, but I can’t formulate the right logic..

(the values together within the string are purposeful: ['A, B', 'C', ’D,E'])

  • Are you sure that the example you gave is the result you would like and not that it was ['Feijao, Arroz', 'Melancia', 'Banana', 'Laranja', 'Uva']?

  • 1

    Absolute. Some values would be grouped in a single string: 'Bean, Rice' , 'Orange, Grape'

1 answer

2


Simply use a regular expression replacement in conjunction with the function map of Array:

let arr = ['Feijao, Arroz', 'Melancia', 'Banana', 'Laranja,Uva'];

arr = arr.map((item) => item.replace(/,([^ ]{1})/g, ', $1'));

console.log(arr);


In regular expression:

  • Matches the character , literally;
  • Catch Grouping ([^ ]{1}):
    • Matches only one character not present in the list [^ ];
    • Quantifier {1} - Matches exactly once the previous list;

We use regular expression to isolate the character that comes after the comma to subsequently replace the whole expression with , + what’s inside the group.


Array.prototype.map()

The map() method invokes the callback function passed by argument to each Array element and returns a new Array as a result.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots é [1, 2, 3], numbers ainda é [1, 4, 9]

Agrupamentos

(x) - Corresponds x and memorizes the match. These are called catch parentheses.

For example, /(foo)/ matches and memorizes "foo" in "foo bar". The matching substring can be called again from the elements of the resulting array [1], ..., [n] or the predefined properties of the object RegExp $1, ..., $9.

  • I liked the solution, but I didn’t understand the second parameter of the replace() function. Could you explain to me what/how this '$1 works'?

  • 1

    @ju4ncrls added a more detailed explanation about expression and regular expression groupings

Browser other questions tagged

You are not signed in. Login or sign up in order to post.