从字符串中删除最后一个逗号

IT技术 javascript
2021-02-17 00:03:35

使用 JavaScript,如何删除最后一个逗号,但前提是逗号是最后一个字符或者逗号后只有空格?这是我的代码。我得到了一个工作小提琴但它有一个错误。

var str = 'This, is a test.'; 
alert( removeLastComma(str) ); // should remain unchanged

var str = 'This, is a test,'; 
alert( removeLastComma(str) ); // should remove the last comma

var str = 'This is a test,          '; 
alert( removeLastComma(str) ); // should remove the last comma

function removeLastComma(strng){        
    var n=strng.lastIndexOf(",");
    var a=strng.substring(0,n) 
    return a;
}
6个回答

这将删除最后一个逗号和它后面的任何空格:

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

它使用正则表达式:

  • /标记的开始和正则表达式的结束

  • ,逗号匹配

  • \s装置的空白字符(空格,制表符,等),和*装置0以上

  • $在最后表示该字符串的结尾

@ParkashKumar Jon has already mentioned about the last /. The / mark the beginning and end of the regular expression.
2021-04-18 00:03:35
Very useful Thanks.
2021-04-20 00:03:35
Use str.replace(/,+/g,",").replace(/(,\s*$)|(^,*)/, ""); if you want to remove the initial empty comma or, double comma, example ",,8,,7" would become "8,7"
2021-05-07 00:03:35

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>