1
I have the text in the string below:
string = "ele, joao gosta de maria, mas maria gosta de jose";
string = string.replace(/???/g,", ");
Note 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 on replace to reach 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 didn’t work out so well. Commas are left over.
The problem is that this regex also replaces the character
|, that is to say:'a|b'.replace(/[,|\s]+/g,", ")results ina, b. To prevent this, remove the|, that is to say:/[,\s]+/g. Another difference to the other answer is that yours also replaces several commas, e.g.:'a,,,,b'becomesa, b, and tb does not require spaces after the comma (a,bbecomesa, b, already the regex of the other answer does not change because it expects at least one space after the comma) - not that it is totally wrong, it is only to point out the differences even :-)– hkotsubo