This code generates a comma separated string to provide a list of ids to the query string of another page, but there is an extra comma at the end of the string. How can I re
Write a javascript function :
var removeLastChar = function(value, char){
var lastChar = value.slice(-1);
if(lastChar == char) {
value = value.slice(0, -1);
}
return value;
}
Use it like this:
var nums = '1,2,3,4,5,6,';
var result = removeLastChar(nums, ',');
console.log(result);
jsfiddle demo
Sam's answer is the best so far, but I think map would be a better choice than each in this case. You're transforming a list of elements into a list of their values, and that's exactly the sort of thing map
is designed for.
var list = $("td.title_listing input:checked")
.map(function() { return $(this).val(); })
.get().join(', ');
Edit: Whoops, I missed that CMS beat me to the use of map
, he just hid it under a slice
suggestion that I skipped over.
A more primitive way is to change the each
loop into a for
loop
for(var x = 0; x < n.length; x++ ) {
if(x < n.length - 1)
s += $(n[x]).val() + ",";
else
s += $(n[x]).val();
}
you can use below extension method:
String.prototype.trimEnd = function (c) {
c = c ? c : ' ';
var i = this.length - 1;
for (; i >= 0 && this.charAt(i) == c; i--);
return this.substring(0, i + 1);
}
So that you can use it like :
var str="hello,";
str.trimEnd(',');
Output: hello.
for more extension methods, check below link: Javascript helper methods
Instead of removing it, you can simply skip adding it in the first place:
var s = '';
n.each(function() {
s += (s.length > 0 ? ',' : '') + $(this).val();
});
You can use the String.prototype.slice method with a negative endSlice
argument:
n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"
Or you can use the $.map method to build your comma separated string:
var s = n.map(function(){
return $(this).val();
}).get().join();
alert(s);