Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace final comma in a string with "and"

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?

like image 500
GtwoK Avatar asked May 01 '15 10:05

GtwoK


2 Answers

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

like image 171
Kobi Avatar answered Oct 19 '22 23:10

Kobi


(.*,)

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);
like image 42
vks Avatar answered Oct 20 '22 01:10

vks