I need to remove the last element comma in Javascript array
var arr = ["AAA,","BBB,"];
I need the result below
var arr = ["AAA,","BBB"];
Any help is appreciated...
I need to remove the last element comma in Javascript array
var arr = ["AAA,","BBB,"];
I need the result below
var arr = ["AAA,","BBB"];
Any help is appreciated...
var arr = ["AAA,","BBB,"];
arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');
console.log(arr);
Simply use with replace()
var arr = ["AAA,","BBB,"];
arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");
console.log(arr)
['ABC,', 'X,Y,Z,'].This answer explains how you can do it using regex:
>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"
[^,]* part in your regex? OP asked about removing a comma, not removing a comma and the characters that follow it.var arr = ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);
Output :
["AAA,", "BBB"]
arr[arr.length-1] = arr[arr.length-1].slice(0,-1)
.slice(0,-1) is a lot more convenient than .slice(0,arr[arr.length-1].length-1).