用jQuery/JavaScript替换,用和替换jQuery/JavaScript的最后一个索引

9 javascript regex string jquery replace

我想用,字符串替换逗号()的最后一个索引and.

例如 a,b,c'a,b and c'

例如, q,w,eq,w and e

Tus*_*har 10

DEMO

lastIndexOf 查找在其中传递的参数字符串的最后一个索引.

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

你也可以使用这个功能

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'));
Run Code Online (Sandbox Code Playgroud)


moh*_*han 8

这个正则表达式应该做的工作

"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
Run Code Online (Sandbox Code Playgroud)