Remove Last Comma from a string

前端 未结 10 1031
轻奢々
轻奢々 2020-11-30 19:52

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? This is my code. I got a wor

相关标签:
10条回答
  • 2020-11-30 19:59

    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);
    
    0 讨论(0)
  • 2020-11-30 20:01

    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.

    0 讨论(0)
  • 2020-11-30 20:03
    function removeLastComma(str) {
       return str.replace(/,(\s+)?$/, '');   
    }
    
    0 讨论(0)
  • 2020-11-30 20:04

    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/

    0 讨论(0)
  • 2020-11-30 20:05

    you can remove last comma:

    var sentence = "I got,. commas, here,";
    sentence = sentence.replace(/(.+),$/, '$1');
    console.log(sentence);
    
    0 讨论(0)
  • 2020-11-30 20:06

    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>

    0 讨论(0)
提交回复
热议问题