How do I remove last comma from string using jQuery or Javascript?


I have a string like "this, is, test," now I want to remove the last "," (comma) from this string to make it like "this, is, test", so How can I remove only last comma from string jQuery or Javascript?

I prefer Javascript method,thanks


Asked by:- jaiprakash
0
: 12670 At:- 11/29/2018 3:59:48 PM
Javascript jQuery remove last comma from string







3 Answers
profileImage Answered by:- jaya

Yes, you can remove last comma using Regex with .replace() function in Javascript

Here is the example of it

var str1 = "This, is, test,";

str1 = str1.replace(/,\s*$/, "");  // output "this, is , test"

Here is the Fiddle working sample  https://jsfiddle.net/xkgy71dr/

function removeExtraComma()
{
 var str1 = "This, is, test,";

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

 document.getElementById("Output").innerHTML =str1;
}

removeExtraComma();

HTML

<div id="Output">

</div>

If you want to remove double comma from a string and make it one, you can use regex

     var str1= "this,,is,test";
 
     //remove extra comma from the middle of the string (if any)
     str1= str1.replace(/^,|,$|(,)+/g, '$1');

    //output : this,is,test
3
At:- 11/30/2018 9:48:05 AM


profileImage Answered by:- vikas_jk

Above method works as needed, but if you don't want to use Regex you can try the below Javascript based function:

function removeLastComma(value) {
	var strVal = (value).trim();
	var lastChar = strVal.slice(-1);
	if (lastChar == ',') { // check last character is string
		strVal = strVal.slice(0, -1); // trim last character
		document.getElementById("Output").value=strVal; //output
	}
}

removeLastComma(document.getElementById("INP").value); //output

HTML

<input type="text" value="text,ajax,sql," id="INP"/>
<input type="text" value="" id="Output"/>

Output:

remove-last-comma-javascript-min.png

https://jsfiddle.net/xqk5w36z/

1
At:- 12/20/2020 1:04:38 PM


profileImage Answered by:- bhanu

Above solutions are great, but if you need non-regex based solution to remove last comma, try this

var str = "Hello,World, without last comma";
var index = str.lastIndexOf(",");
str = str.substring(0, index) + str.substring(index + 1);

This is based on substring and lastIndexOf JS string functions.

0
At:- 4/19/2022 3:43:22 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use