I've got a string that is generated, and is essentially a list of things. This string is something that will be read by the user, so I'm trying to formate it nicely. I am separating the generated list using commas and spaces:
(a+'').replace(/,/g, ", ");
produces
1, 2, 3, 4
However, I'd like to change the last comma to ", and", so that it reads
1, 2, 3, and 4
I've tried the following:
((a+'').replace(/,/g, ", ")).replace(/,$/, ", and");
but it doesn't work, which I THINK is because that is only looking for commas at the end of the string, rather than the last comma in the string, right?
As well, if there are only 2 items in the string, I want the comma to be replaced with just "and", rather than ", and", to make more sense grammatically.
How can I achieve what I'm looking for?
You probably want
,(?=[^,]+$)
for example:
"1, 2, 3, 4".replace(/,(?=[^,]+$)/, ', and');
(?=[^,]+$)
checks that there are no more commas after this comma. (?!.*,)
would also work.
You can even check there isn't already an and
:
,(?!\s+and\b)(?=[^,]+$)
Working example: https://regex101.com/r/aE2fY7/2
(.*,)
You can use this simple regex.Replace by $1 and
or \1 and
.See demo.
https://regex101.com/r/uE3cC4/8
var re = /(.*,)/gm;
var str = '1, 2, 3, 4';
var subst = '$1 and';
var result = str.replace(re, subst);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With