Consider, we have the following string with a number of commas:
Now, we want to remove the last comma from the string above.
slice() Method by transferring the
0, -1 As arguments for this.
The slice () method uses negative indexes to access characters from the end of the string.
Here’s an example, which removes the last comma from the next string.
const str = "a,b,c,"; const result = str.slice(0, -1); console.log(result);
In the example above, we moved on
0, -1 As arguments to
slice() method. So it starts the extraction in the index position
0, And extracts before the last character of a string.
Similarly, we can also use
substring() Method for removing the last comma of a string.
const str = "a,b,c,"; const result = str.substring(0, str.length-1); console.log(result);
In the code above, we have passed two arguments to
substring() The first method is the Start Index
0 And the second is the end index (which is not included in the final output).
substring()Methods do not change the original string.