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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17986123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:20:14  来源:igfitidea点击:

Replace last index of , with and in jQuery /JavaScript

javascriptjqueryregexstringreplace

提问by Tushar Gupta - curioustushar

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

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

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

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

eg q,w,ewith q,w and e

例如 q,w,eq,w and e

回答by Tushar Gupta - curioustushar

DEMO

演示

lastIndexOffinds the last index of the parameter string passed in it.

lastIndexOf查找传入的参数字符串的最后一个索引。

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

回答by mohkhan

This regex should do the job

这个正则表达式应该可以完成这项工作

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

回答by Anand

Try the following

尝试以下

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

回答by Neeraj Dubey

Try

尝试

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

alert(str)

Fiddle Demo

小提琴演示

回答by Alok Agarwal

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.

这将解决您的目的。