2013-08-01 9 views

risposta

8

DEMO

lastIndexOf trova l'ultimo indice della stringa parametro passato in esso.

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

è anche possibile utilizzare questa funzione

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')); 
7

Questa regex dovrebbe fare il lavoro

"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2") 
2

provare il seguente

var x= 'a,b,c,d'; 
x = x.replace(/,([^,]*)$/, " and $1"); 
0

Prova

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

alert(str) 

Fiddle Demo

0

Un ciclo semplice vi aiuterà a uscire

prima trovare l'indice di tutti, nella stringa utilizzando,

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]] = '.' 

Questo risolverà il vostro scopo.