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.
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);
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).
substring()methods does not modify the original string.