Categories
JavaScript Answers

How to remove last comma from a string with JavaScript?

Spread the love

Sometimes, we want to remove last comma from a string with JavaScript.

In this article, we’ll look at how to remove last comma from a string with JavaScript.

How to remove last comma from a string with JavaScript?

To remove last comma from a string with JavaScript, we can use the string replace method.

For instance, we write

const newStr = str.replace(/,\s*$/, "");

to call str.replace with a regex that matches the comma at the end of the string or before the whitespaces that’s at the end of the string.

And we call it with an empty string to replace the commas with an empty string.

Conclusion

To remove last comma from a string with JavaScript, we can use the string replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *