Remove Last Comma from a string

前端 未结 10 1032
轻奢々
轻奢々 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 20:09

    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>

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

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

    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

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

    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)

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