Reputation: 142
I'm building a string based on selected checkboxes. I wrote a statement that will add pluralization if there are multiple strings selected, but I cannot figure out how to remove the last two commas that are put into the 'policyHidden' field by the array.
$(document).ready(function(){
$('input:checkbox').change(function() {
var keys = [];
var policies = $('input:checkbox:checked').map(function () {
return $(this).siblings('span').text(); }).get();
$.each(policies, function(key, value) { keys.push(value) });
output = keys.join(", ");
FormSetFieldValue('policyHidden', output);
if (keys.length > 1) {
keys.splice(keys.length - 1, 0, "and");
}
FormSetFieldValue('policyHidden', output);
});
});
example output is
value1, value2, and, value3
I just want to remove the last two commas. should I do a regex?
FYI, FormSetFieldValue is a function from another script; first variable calls the variable wanting to be changed, second one is the set value. Shouldn't have any consequence on the problem at hand.
Upvotes: 0
Views: 81
Reputation: 220136
I think putting it in there - and then removing it - is counter-intuitive.
You shouldn't put it into your string that way in the first place:
var output = [];
output[1] = keys.pop();
output[0] = keys.join(', ');
output = output.join(' and ');
Here's the fiddle: http://jsfiddle.net/yfKjp/
Upvotes: 1
Reputation: 2229
regex is a one option. you can also do a javascript replace function for ', and,' with ' and'
var str = "value1, value2, and, value3"
str.replace(', and,',' and')
you may have to escape the commas.
Upvotes: 1