How to remove the last comma of a string in JavaScript
In this tutorial, we are going to learn about how to remove the last character of a given string in JavaScript.
Consider, we have the following string with multiple commas:
const str = "a,b,c,";
Now, we want to remove the last comma from the above string.
Removing the last comma
To remove the last comma of a string in JavaScript, we can use the built-in slice()
method by passing the 0, -1
as arguments to it.
In the slice() method, negative indexes are used to access the characters from the end of a string.
Here is an example, that removes the last comma from the following string.
const str = "a,b,c,";
const result = str.slice(0, -1);
console.log(result);
Output:
"a,b,c"
In the example above, we have passed 0, -1
as arguments to the slice()
method. so it begins the extraction at index position 0
, and extracts before the last character of a string.
Similarly, we can also use the substring()
method to remove the last comma of a string.
const str = "a,b,c,";
const result = str.substring(0, str.length-1);
console.log(result);
In the above code, we have passed two arguments to the substring()
method, the first one is start index 0
and the second one is the end index (which is not included in the final output).
Note: The
slice()
andsubstring()
methods does not modify the original string.