Remove last comma if last character is comma. First we have to check the last character in given string is comma or not. If last character is comma then we remove the last character.
You can remove any last specific character if it exists at last position with the help of given example.
var ids = '1,2,3,4,';
var lastChar = ids.slice(-1);
if(lastChar == ',') {
ids = ids.slice(0, -1);
}
CODE
<!DOCTYPE html> <html> <head> <title>jQuery With Example</title> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('.btnCheck').click(function (event) { var ids = $('.txtValue').val(); var lastChar = ids.slice(-1); if (lastChar == ',') { ids = ids.slice(0, -1); } alert(ids); }); }); </script> </head> <body> <div> <input type="text" class="txtValue" value="1,2,3,4," /><br /><br /> <button class="btnCheck">Check</button> </div> </body> </html>
DISPLAY
What if there are multiple commas at the end of the string.
ReplyDeletefor ex. '1,2,3,4,,,, ,,'
It will remove only last comma.
DeleteIf you want to remove all comma from last then please use while condition with my code.