Today, I'm going to discuss two ways you can use to remove the last comma from a string in JavaScript.

If you're working on a project and realize that your code has an extra comma at the end of a variable, don't worry! This article will show you how to remove the extra comma.

  1. Remove Last Comma from String Using replace() Method. #

    You can use the replace() method to remove the last comma from a string. The syntax of the replace() method is given below.

    string.replace(searchValue, replaceValue)

    So, to remove the last comma from a string, you can use the following code.

    <script>
      let myString = "This is, a sample string,,";
      let newString = myString.replace(/,,/g,',');
      console.log(newString)
    </script>
  2. Remove Last Comma from String Using slice() Method #

    Using the slice() method is another great way to remove the last character from a string. This method works by taking two parameters – start index and end index.

    <script>
      let myString = "This is, a sample string,,";
      let newString = myString.slice(0,-1);
      console.log(newString)
    </script>