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
: 28 At:- 11/29/2018 3:59:48 PM
Javascript jQuery remove last comma from string






1 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
1
At:- 11/30/2018 9:48:05 AM





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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly