Date:

Share:

How to remove the last comma of a string in JavaScript

Related Articles

In this tutorial, we are going to learn how to remove the last character of a given string in JavaScript.

Consider, we have the following string with a number of commas:

Now, we want to remove the last comma from the string above.

Removing the last comma

To remove the last comma of a string in JavaScript, we can use the built-in connection 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);

Productivity:

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).

Note: e slice() and substring() Methods do not change the original string.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles