Regex to replace comma and spaces together

Asked

Viewed 1,646 times

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.

2 answers

5


This regex works well:

(,?\s+)

Entree:

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

Exit:

"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

,? picked up by a comma that may or may not be there (optional).

\s+ picked up by one or more spaces.

1

The response of @Francis I thought better, but I also managed with this regex below, which I will leave here as reference:

[,|\s]+

A regex casa any occurrence of comma and/or sequence of spaces.

Testing:

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

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

console.log(string);

  • The problem is that this regex also replaces the character |, that is to say: 'a|b'.replace(/[,|\s]+/g,", ") results in a, 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' becomes a, b, and tb does not require spaces after the comma (a,b becomes a, 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 :-)

Browser other questions tagged

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