Replace the trailing comma in the string with "and"

I have a line that is generated, and is essentially a list of things. This line is what the user will read, so I'm trying to create it well. I separate the generated list with commas and spaces:

(a+'').replace(/,/g, ", "); 

produces

 1, 2, 3, 4 

However, I would like to change the last comma to ", and" so that it reads

 1, 2, 3, and 4 

I tried the following:

 ((a+'').replace(/,/g, ", ")).replace(/,$/, ", and"); 

but it does not work, and I think, because it is only a search for commas at the end of the line, and not the last comma in the line, right?

Also, if there are only 2 elements in a line, I want the comma to be replaced simply with "and", and not with "and", to make more sense grammatically.

How can I achieve what I am looking for?

+5
source share
4 answers

You probably want

 ,(?=[^,]+$) 

eg:

 "1, 2, 3, 4".replace(/,(?=[^,]+$)/, ', and'); 

(?=[^,]+$) checks that there are no more commas after this comma. (?!.*,) will also work.

You can even check that there is no and :

 ,(?!\s+and\b)(?=[^,]+$) 

Working example: https://regex101.com/r/aE2fY7/2

+5
source
 (.*,) 

You can use this simple regex.Replace on $1 and or \1 and . See the 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); 
+4
source

What about:

 ((a+'').replace(/,/g, ", ")).replace(/,([^,]*)$/, ", and $1"); 
0
source
 var index = a.lastIndexOf(','); a.replaceAt(index, ', and'); 

Where:

 String.prototype.replaceAt=function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); } 
-1
source

All Articles