简体   繁体   English

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

[英]Remove Last Comma from a string

Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma?使用 JavaScript,如何删除最后一个逗号,但前提是逗号是最后一个字符或者逗号后只有空格? This is my code.这是我的代码。 I got a working fiddle .我有一个工作小提琴 But it has a bug.但它有一个错误。

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

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 \s表示空白字符(空格、制表符等), *表示 0 或更多

  • 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 :您可以使用 slice() 方法从字符串中删除最后一个逗号,找到以下示例

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

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>

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/ https://jsfiddle.net/dc8moa3k/

long shot here在这里远射

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);

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.indexOf(',', this.length - ','.length) 可以简化为 str.indexOf(',', this.length - 1)

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.所以你应该放一个 if 来检查最后一个字符是否是',',如果是,就改变它。

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.您的代码从字符串中找到最后一个逗号并仅存储 'This, ',因为最后一个逗号在 'This' 之后而不是字符串的末尾。

A late answer but probably should help someone. 答案迟到但可能应该帮助某人。

For removing any last char from a string. 用于从字符串中删除任何最后一个字符。

 var str = "one, two, three,"; var str2 = str.substring(0, str.length - 1); alert(str); alert(str2); 

With or without Regex.有或没有正则表达式。

I suggest two processes and also consider removing space as well.我建议两个过程,并且还考虑删除空间。 Today I got this problem and I fixed this by writing the below code.今天我遇到了这个问题,我通过编写以下代码解决了这个问题。

I hope this code will help others.我希望这段代码对其他人有所帮助。

 //With the help of Regex var str = " I am in Pakistan, I am in India, I am in Japan, "; var newstr = str.replace(/[, ]+$/, "").trim(); console.log(newstr); //Without Regex function removeSpaceAndLastComa(str) { var newstr = str.trim(); var tabId = newstr.split(","); strAry = []; tabId.forEach(function(i, e) { if (i != "") { strAry.push(i); } }) console.log(strAry.join(",")); } removeSpaceAndLastComa(str);

If you are targeting es6, then you can simply do this如果您的目标是 es6,那么您可以简单地执行此操作

str = Array.from( str ).splice(0, str.length - 1).join('');
  • This Array.from(str) converts the string to an array (so we can slice it)Array.from(str)将字符串转换为数组(因此我们可以对其进行切片)

  • This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the arraysplice( 0 , str.length - 1 )返回一个数组,其中包含数组中的项目,但数组中的最后一项除外

  • This join('') joins the entries in the array to form a string这个join('')将数组中的条目连接起来形成一个字符串

Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this然后,如果您想在执行操作之前确保逗号实际上结束了字符串,您可以执行以下操作

str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;

To remove the last comma from a string, you need要从字符串中删除最后一个逗号,您需要

text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')

See the regex demo .请参阅正则表达式演示 Details :详情

  • ,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string. ,(?=[^,]*$) - 一个逗号,后面紧跟除逗号之外的任何零个或多个字符,直到字符串结尾。
  • ,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma. ,(?![^,]*,) - 一个逗号,其后不紧跟任何零个或多个字符,除了一个逗号,然后是另一个逗号。

See the JavaScript demo:请参阅 JavaScript 演示:

 const text = '1,This is a test, and this is another, ...'; console.log(text.replace(/,(?=[^,]*$)/, '')); console.log(text.replace(/,(?![^,]*,)/, ''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM