AnaMaria
AnaMaria

Reputation: 3621

Remove last comma (and possible whitespaces after the last comma) from the end of 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? 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;
}

Upvotes: 202

Views: 302413

Answers (14)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

To remove the last comma from a string even if there are characters after it (which is different from what has been asked), 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:

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

Upvotes: 1

Arqam Rafay
Arqam Rafay

Reputation: 135

Remove whitespace and comma at the end use this,

var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"

Upvotes: 1

Henry Obiaraije
Henry Obiaraije

Reputation: 458

If you are targeting es6, then you can simply do this

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)

  • This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array

  • This join('') joins the entries in the array to form a string

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;

Upvotes: 0

Zaid Bin Khalid
Zaid Bin Khalid

Reputation: 763

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

Upvotes: 0

Komal
Komal

Reputation: 1097

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>

Upvotes: 8

Booboo
Booboo

Reputation: 44323

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/

Upvotes: 6

Max Alexander Hanna
Max Alexander Hanna

Reputation: 3871

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)

Upvotes: 3

e-techpulse
e-techpulse

Reputation: 551

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>

Upvotes: 20

Deepu Reghunath
Deepu Reghunath

Reputation: 9713

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>

Upvotes: 3

Trai Hải Ph&#242;ng
Trai Hải Ph&#242;ng

Reputation: 31

you can remove last comma:

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

Upvotes: 2

Hristo Valkanov
Hristo Valkanov

Reputation: 1687

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.

Upvotes: -1

user2587132
user2587132

Reputation:

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

Upvotes: 2

Daniel Sloof
Daniel Sloof

Reputation: 12706

function removeLastComma(str) {
   return str.replace(/,(\s+)?$/, '');   
}

Upvotes: 20

Jon
Jon

Reputation: 13002

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

Upvotes: 546

Related Questions