I have a variable string in my JavaScript code containing a comma delimited list of words and or phrases, for example:
String 1 : “abc, def hij, klm”
String 2 : “abc, def”
I want to insert the word ‘and’ after the last comma in the string to get
String 1 : “abc, def hij, and klm”
String 2 : “abc, and def”
I put together the following code:
// replace the last comma in the list with ", and"
var regEx1 = new RegExp(",(?=[A-z ]*$)" )
var commaDelimList = commaDelimList.replace(regEx1, ", and ");
The problem is that it does not work if the comma delimited string has only two items separated by one comma.
So the results of the above example are
String 1 : ”abc, def hij, and klm”
String 2 : “abc, def”
Why is the RegExp not working and what can I use to get the result I want?
Not sure a regex was the right way to go there…
Why not use LastIndexOf and replace that with your string?