如何从最后一个数组元素中删除字符

时间:2017-03-30 04:55:52

标签: javascript

我需要删除Javascript数组中的最后一个元素逗号

var arr =  ["AAA,","BBB,"];

我需要以下结果

var arr =  ["AAA,","BBB"];

感谢任何帮助...

7 个答案:

答案 0 :(得分:3)

var arr =  ["AAA,","BBB,"];

arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');

console.log(arr);

答案 1 :(得分:1)

只需与replace()一起使用

var arr =  ["AAA,","BBB,"];

arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");

console.log(arr)

答案 2 :(得分:0)

arr[arr.length-1] = arr[arr.length-1].slice(0,-1)

答案 3 :(得分:0)

另一种方式是:



var arr =  ["AAA,",",BBB,"];
arr.push(arr.pop().replace(/,$/, ''));
console.log(arr);




答案 4 :(得分:0)

This回答说明如何使用正则表达式执行此操作:

>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"

答案 5 :(得分:0)

var arr =  ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);

输出:

["AAA,", "BBB"]

答案 6 :(得分:0)

使用JavaScript字符串split()方法&数组splice()方法。

<强>样本

var arr =  ["AAA,","BBB,"];

var arrLastElement = arr[arr.length-1];

var splitStr =  arrLastElement.split(',');

var strWithoutComma = splitStr[0];

arr.splice(arr.length-1);
arr.push(strWithoutComma);

console.log(arr);