Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Last Comma from a string

Tags:

javascript

People also ask

How do I remove the last comma in Python?

Just use rstrip().

How do I remove the last comma in a string in C++?

To easily remove the last comma you can use the '\b' character.

How do I remove the last comma in Unix?

sed 's/\(. *\),/\1/' file will remove last , in all lines in the file.


This will remove the last comma and any whitespace after it:

str = str.replace(/,\s*$/, "");

It uses a regular expression:

  • The / mark the beginning and end of the regular expression

  • The , matches the comma

  • The \s means whitespace characters (space, tab, etc) and the * means 0 or more

  • The $ at the end signifies the end of the string


you can remove last comma from a string by using slice() method, find the below example:

var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
    strVal = strVal.slice(0, -1);
}

Here is an Example

function myFunction() {
	var strVal = $.trim($('.txtValue').text());
	var lastChar = strVal.slice(-1);
	if (lastChar == ',') { // check last character is string
		strVal = strVal.slice(0, -1); // trim last character
		$("#demo").text(strVal);
	}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p class="txtValue">Striing with Commma,</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

function removeLastComma(str) {
   return str.replace(/,(\s+)?$/, '');   
}

The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:

let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '

https://jsfiddle.net/dc8moa3k/


In case its useful or a better way:

str = str.replace(/(\s*,?\s*)*$/, "");

It will replace all following combination end of the string:

1. ,<no space>
2. ,<spaces> 
3. ,  ,  , ,   ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>