Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to replace last comma with "and " in a string using javascript [duplicate]

Tags:

javascript

I want to replace last comma in a string with and... for eg

var ambassadorName = test, test, test

the output must be

var ambassadorName= test, test and test. 

Please help me with the code

like image 345
user3756425 Avatar asked Sep 04 '14 05:09

user3756425


2 Answers

Using regex you can do:

ambassadorName.replace(/,(?=[^,]*$)/, ' and')

I hope it works.

like image 187
bribeiro Avatar answered Oct 19 '22 16:10

bribeiro


You can do it like this:

var ambassadorName = "test, test, test";
ambassadorName = ambassadorName.replace(/,([^,]*)$/, 'and $1');
like image 5
Viswanath Donthi Avatar answered Oct 19 '22 16:10

Viswanath Donthi