Regex to replace commas and spaces together

1

I have the text in the string below:

string = "ele, joao     gosta  de   maria,   mas   maria gosta        de jose";

string = string.replace(/???/g,", ");

See that some words have more or less spaces between them, and may still have commas after a word, but never a space before a comma.

How to build a Regex in replace to get the result below?

ele, joao, gosta, de, maria, mas, maria, gosta, de, jose

That is, each word separated by a comma and a space .

I tried something like this: string = string.replace(/,\s+/g,", "); but it did not work very well. Comma left over.

    
asked by anonymous 01.04.2018 / 01:40

2 answers

5

This regex works fine:

(,?\s+)

Entry:

"ele, joao     gosta  de   maria,   mas   maria gosta        de jose"

Output:

"ele, joao, gosta, de, maria, mas, maria, gosta, de, jose"

let string = "ele, joao     gosta  de   maria,   mas   maria gosta        de jose"

string = string.replace(/,?\s+/g, ", ")

console.log(string)

Explanation

,? gets a comma that may or may not be there (optional).

\s+ takes one or more spaces.

    
01.04.2018 / 02:02
0

The answer from @Francisco I thought better, but I also managed with this regex below, which I will leave here as reference:

[,|\s]+

The regex matches any occurrence of comma and / or spaces sequence.

Test:

string = "ele, joao     gosta  de   maria,   mas   maria gosta        de jose";

string = string.replace(/[,|\s]+/g,", ");

console.log(string);
    
01.04.2018 / 02:36