If the commas you want to delete always have a space before, just include the space in the regex:
let texto = 'Cód: mrkk-918278 ,Título: Blusa-02 ,Preço: R$ 60,50 ,Qtd: 1 ,Cód: mrkk-918277 ,Título: Blusa manga longa ,Preço: R$ 50,50 ,Qtd: 1 ,Cód: mrkk-918279 ,Título: Blusa-03 ,Preço: R$ 70,25 ,Qtd: 1 ,Cód: mrkk-918280 ,Título: Blusa-04 ,Preço: R$ 100,25 ,Qtd: 2 Total: R$ 381,75';
texto = texto.replace(/ ,/g, ' ');
console.log(texto);
I mean, I change ,
(a space followed by a comma) for ' '
(only one space). If you have more than one space, you could even use /\s+,/g
, so one or more spaces followed by comma are exchanged for a single space. Adapt to your case.
But if you have an array (guess, because the variable is called novoArray
), it makes no sense to turn it into string with toString()
and then remove the commas. It’s an unnecessary turn because toString
returns the elements of the semicolon-separated array, so instead of adding this comma and then removing it, it would be better to join the elements in another way.
An alternative is to use join
to join all array elements into a single string, and you choose the text that goes between the elements. In the example below, I chose a space:
let novoArray = ['Cód: mrkk-918278', 'Título: Blusa-02', 'Preço: R$ 60,50',
'Qtd: 1', 'Cód: mrkk-918277', 'Título: Blusa manga longa', 'Preço: R$ 50,50',
'Qtd: 1', 'Cód: mrkk-918279', 'Título: Blusa-03', 'Preço: R$ 70,25',
'Qtd: 1', 'Cód: mrkk-918280', 'Título: Blusa-04', 'Preço: R$ 100,25',
'Qtd: 2 Total: R$ 381,75'];
// junta os elementos do array, separando-os por um espaço
console.log(novoArray.join(' '));
Thus you avoid all this unnecessary turn of adding the commas and then using a regex to remove them. With join
you choose the text that goes between the elements and you won’t even need the regex.
Welcome to Stack Overflow in English. This code may be a solution to the question, but your answer might be better if you include an explanation of the key points of the code. The goal is not only to help those who asked the question, but the next visitors as well. Read more on Code-only answers - What to do?.
– Rafael Tavares
Dear Alexander. It worked!! Thanks for the promptness. (perfect)
– Shin