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
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
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:
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly