Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用和替换jQuery/JavaScript中的最后一个索引_Javascript_Jquery_Regex_String_Replace - Fatal编程技术网

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

用和替换jQuery/JavaScript中的最后一个索引,javascript,jquery,regex,string,replace,Javascript,Jquery,Regex,String,Replace,我想用和替换字符串中逗号(,)的最后一个索引 例如a、b、c与'a、b和c' 例如q,w,e与q,w和e lastIndexOf查找传入的参数字符串的最后一个索引 var x = 'a,b,c'; var pos = x.lastIndexOf(','); x = x.substring(0,pos)+' and '+x.substring(pos+1); console.log(x); 您也可以使用此功能 function replace_last_comma_with_and(x) {

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

例如<代码>a、b、c与
'a、b和c'

例如
q,w,e
q,w和e

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

var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);
您也可以使用此功能

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'));
使用正则表达式的替代解决方案:

function replaceLastCommaWith(x, y) {
  return x.replace(/,(?=[^,]*$)/, " " + y + " ");
}
console.log(replaceLastCommaWith("a,b,c,d", "and")); //a,b,c and d
console.log(replaceLastCommaWith("a,b,c,d", "or")); //a,b,c or d

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

"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
试试下面的方法

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


一个简单的循环将帮助您解决问题

首先在字符串中使用

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]] = '.'
var str=“a、b、c、d、e”;
var指数=[];
对于(var i=0;i
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]] = '.'