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

2020/11/16 16:22 · javascript ·  · 0评论

使用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;
}

这将删除最后一个逗号及其后的所有空格:

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

它使用一个正则表达式:

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

  • ,逗号匹配

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

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

您可以使用slice()方法从字符串中删除最后一个逗号,请找到以下示例

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

这是一个例子

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+)?$/, '');   
}

高度支持的答案不仅删除了最后的逗号,而且还删除了后面的所有空格。但是删除这些空格并不是原来问题的一部分。所以:

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

https://jsfiddle.net/dc8moa3k/

这里远射

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.

EDIT: Is it really that confusing?

'This, is a random string'

Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.

you can remove last comma:

var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);

Remove last comma. Working example

function truncateText() {
  var str= document.getElementById('input').value;
  str = str.replace(/,\s*$/, "");
  console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>

First, one should check if the last character is a comma.
If it exists, remove it.

if (str.indexOf(',', this.length - ','.length) !== -1) {
    str = str.substring(0, str.length - 1);
}

NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)

如果它有用或更好的方法:

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

它将替换字符串的所有以下组合结尾:

1. ,<no space>
2. ,<spaces> 
3. ,  ,  , ,   ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
本文地址:http://javascript.askforanswer.com/congzifuchuanzhongshanchuzuihouyigedouhao.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!