Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

i want to replace the last index of comma (,)in string with and.

eg . a,b,c with 'a,b and c'

eg q,w,e with q,w and e

share|improve this question
up vote 5 down vote accepted

DEMO

lastIndexOf finds the last index of the parameter string passed in it.

var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);

you can also use this function

function replace_last_comma_with_and(x) {
    var pos = x.lastIndexOf(',');
    return x.substring(0, pos) + ' and ' + x.substring(pos + 1);
}
console.log(replace_last_comma_with_and('a,b,c,d'));
share|improve this answer

This regex should do the job

"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
share|improve this answer

Try the following

var x= 'a,b,c,d';
x = x.replace(/,([^,]*)$/, " and $1");
share|improve this answer

Try

var str = 'a,b,c', replacement = ' and ';
str = str.replace(/,([^,]*)$/,replacement+'$1'); 

alert(str)

Fiddle Demo

share|improve this answer

A simple loop will help you out

first find the index of all , in your string using,

var str = "a,b,c,d,e";
var indices = [];
for(var i=0; i<str.length;i++) {
    if (str[i] === ",") indices.push(i);
}


indices = [1,3,5,7] as it start from 0

len = indices.length()
str[indices[len - 1]] = '.'

This will solve your purpose.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.