Remove the last Comma from a String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
8 min

banner

# Table of Contents

  1. Remove the last Comma from a String in JavaScript
  2. Remove the last comma from a string regardless if it's at the end
  3. Remove the Leading and Trailing Comma from a String
  4. Removing multiple leading and trailing commas from a string

# Remove the last Comma from a String in JavaScript

Use the replace() method to remove the last comma from a string, e.g. str.replace(/,*$/, '');.

The replace method will remove the last comma from the string by replacing it with an empty string.

index.js
const str = 'apple,banana,kiwi,'; const lastCommaRemoved = str.replace(/,*$/, ''); console.log(lastCommaRemoved); // ๐Ÿ‘‰๏ธ "apple,banana,kiwi"

remove last comma from string in javascript

The code for this article is available on GitHub
If you're looking to avoid using regular expressions, scroll down to the next examples.

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The forward slashes / / mark the beginning and end of the regular expression.

index.js
const str = 'apple,banana,kiwi,'; const lastCommaRemoved = str.replace(/,*$/, ''); console.log(lastCommaRemoved); // ๐Ÿ‘‰๏ธ "apple,banana,kiwi"

The asterisk * matches the preceding item (the comma) 0 or more times.

The dollar $ sign matches the end of the input.

In its entirety, the regular expression matches 0 or more commas at the end of the string.

This approach would also work if the string ends with multiple commas.

index.js
const str = 'apple,banana,kiwi,,,,,,'; const lastCommaRemoved = str.replace(/,*$/, ''); console.log(lastCommaRemoved); // ๐Ÿ‘‰๏ธ "apple,banana,kiwi"

If your string might also contain trailing whitespace after the comma that you want to remove, use the \s special character.

index.js
const str = 'one,two,three, '; const lastCommaRemoved = str.replace(/,\s*$/, ''); console.dir(lastCommaRemoved); // ๐Ÿ‘‰๏ธ 'one,two,three'

The \s special character matches spaces, tabs and new lines.

In its entirety, the regular expression matches one or more trailing commas and whitespace characters at the end of the string and then removes them by replacing them with an empty string.

If the string doesn't end with a comma (the regular expression doesn't match anything), so the replace() method returns the entire string without removing anything.

index.js
const str = 'apple,banana,kiwi'; const lastCommaRemoved = str.replace(/,*$/, ''); console.log(lastCommaRemoved); // ๐Ÿ‘‰๏ธ "apple,banana,kiwi"

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

# Remove the last comma from a string regardless if it's at the end

If you need to remove the last comma from a string, regardless if it's at the end of the string, use the String.lastIndexOf() method.

index.js
function removeLastComma(str) { const lastIndex = str.lastIndexOf(','); if (lastIndex !== -1) { return str.slice(0, lastIndex) + str.slice(lastIndex + 1); } return str; } console.log(removeLastComma('a,b,c')); // ๐Ÿ‘‰๏ธ a,bc console.log(removeLastComma('a,b,c,')); // ๐Ÿ‘‰๏ธ a,b,c console.log(removeLastComma('abc')); // ๐Ÿ‘‰๏ธ abc

remove last comma from string regardless if its at the end

The code for this article is available on GitHub

The String.lastIndexOf() method returns the index of the last occurrence of a substring in a string.

The method returns -1 if the substring is not contained in the string.

If the string contains a comma, we use the String.slice() method to exclude the character at that index, otherwise, we return the string as is.

This approach removes the last comma from the string even if it's not at the end.

Alternatively, you can use the String.endsWith() method.

# Remove the last Comma from a String using String.endsWith()

This is a three-step process:

  1. Use the endsWith() method to check if the string ends with a comma.
  2. If it does, use the slice() method to get a portion of the string, excluding the last comma.
  3. If it doesn't, return the string as is.
index.js
const str = 'avocado,grapefruit,orange'; const lastCommaRemoved = str.endsWith(',') ? str.slice(0, -1) : str; // ๐Ÿ‘‡๏ธ "avocado,grapefruit,orange" console.log(lastCommaRemoved);

remove last comma from string using string endswith

The code for this article is available on GitHub

The String.endsWith() method returns true if the string ends with the specified substring and false otherwise.

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

If the string ends with a comma, we use the slice() method to get a new string excluding the last character of the original string.

The String.slice() method can be passed negative indexes to count backward.

index.js
console.log('bobbyhadz.com'.slice(0, -1)); // ๐Ÿ‘‰๏ธ bobbyhadz.co console.log('bobbyhadz.com'.slice(0, -2)); // ๐Ÿ‘‰๏ธ bobbyhadz.c

If the string doesn't end with a comma, we return it as is.

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

Passing an end index of -1 and str.length - 1 is the same.

We instruct the slice() method to go up to, but not including the last character of the string.

This approach only removes the last comma from the string.

It doesn't handle a scenario where the string ends with multiple commas. If you need to handle that, use the regex approach instead.

Alternatively, you can use the String.lastIndexOf method.

# Remove the last Comma from a String using lastIndexOf

This is a three-step process:

  1. Use the lastIndexOf() method to check if the last character in the string is a comma.
  2. If it is, use the slice() method to exclude the last character.
  3. If it isn't, return the string as is.
index.js
const str = 'one,two,three,'; const lastCommaRemoved = str.lastIndexOf(',') === str.length - 1 ? str.slice(0, -1) : str; console.log(lastCommaRemoved); // ๐Ÿ‘‰๏ธ "one,two,three"

remove last comma from string using lastindexof

The code for this article is available on GitHub

We used the lastIndexOf() method to check if the last character in the string is a comma.

If the condition is met, we return the result of calling the str.slice() method and remove the last comma from the string.

Otherwise, we return the entire string without removing anything.

# Remove the Leading and Trailing Comma from a String

To remove the leading and trailing comma from a string, call the replace() method with a regular expression that matches a comma at the start and end of the string.

The method will remove the leading and trailing comma from the string by replacing them with empty strings.

index.js
const str = ',bobby,hadz,com,'; // โœ… Remove leading and trailing comma from a string const result = str.replace(/(^,)|(,$)/g, ''); console.log(result); // ๐Ÿ‘‰๏ธ "bobby,hadz,com"
The code for this article is available on GitHub
If you're looking to avoid using regular expressions, scroll down to the next subheading.

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The forward slashes / / mark the beginning and end of the regular expression.

index.js
const str = ',bobby,hadz,com,'; const result = str.replace(/(^,)|(,$)/g, ''); console.log(result); // ๐Ÿ‘‰๏ธ "bobby,hadz,com"

The caret ^ matches the beginning of the input and the dollar sign $ matches the end of the input.

We used the pipe | (OR) special character to match a comma at the beginning or a comma at the end of the string.

We used the g (global) flag to match not just the first occurrence (the comma in the beginning), but also the comma at the end of the string.

# Removing multiple leading and trailing commas from a string

If your string might contain multiple leading and trailing commas, use the plus + special character.

index.js
const str = ',,,bobby,hadz,com,,,'; // โœ… Remove leading and trailing comma from a string const result = str.replace(/(^,+)|(,+$)/g, ''); console.log(result); // ๐Ÿ‘‰๏ธ "bobby,hadz,com"
The code for this article is available on GitHub

The plus + matches the preceding item (leading or trailing commas) 1 or more times.

If the string contains no leading or trailing commas, the replace method returns a copy of the string.

index.js
const str = 'bobby,hadz,com'; const result = str.replace(/(^,+)|(,+$)/g, ''); console.log(result); // ๐Ÿ‘‰๏ธ "bobby,hadz,com"

If you have to do this often, define a reusable function.

index.js
function removeLeadingTrailingComma(str) { return str.replace(/(^,+)|(,+$)/g, ''); } // ๐Ÿ‘‡๏ธ bobby,hadz console.log(removeLeadingTrailingComma(',bobby,hadz,')); // ๐Ÿ‘‡๏ธ bobby,hadz,com console.log(removeLeadingTrailingComma(',bobby,hadz,com,'));

The function takes a string as a parameter and removes the leading and trailing commas from the string.

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

# Removing the leading and trailing comma from string using startsWith

This is a three-step process:

  1. Use the startsWith() method to check if the string starts with a comma.
  2. Use the endsWith() method to check if the string ends with a comma.
  3. If the conditions are met, use the slice() method to remove the leading and trailing comma.
index.js
function removeLeadingTrailingComma(str) { if (str.startsWith(',') && str.endsWith(',')) { return str.slice(1, -1); } if (str.startsWith(',')) { return str.slice(1); } if (str.endsWith(',')) { return str.slice(0, -1); } return str; } // ๐Ÿ‘‡๏ธ "bobby,hadz,com" console.log(removeLeadingTrailingComma(',bobby,hadz,com,')); // ๐Ÿ‘‡๏ธ "bobby,hadz,com" console.log(removeLeadingTrailingComma('bobby,hadz,com,')); // ๐Ÿ‘‡๏ธ "bobby,hadz,com" console.log(removeLeadingTrailingComma(',bobby,hadz,com')); // ๐Ÿ‘‡๏ธ "bobby,hadz,com" console.log(removeLeadingTrailingComma('bobby,hadz,com'));
The code for this article is available on GitHub

We handle multiple scenarios:

  1. The string contains both a leading and a trailing comma.
  2. The string contains only a leading comma.
  3. The string contains only a trailing comma.
  4. The string contains no leading or trailing commas.

The String.startsWith() method returns true if the string starts with the specified substring and false otherwise.

index.js
const str = ',bobby,hadz,com'; console.log(str.startsWith(',')); // ๐Ÿ‘‰๏ธ true console.log(str.endsWith(',')); // ๐Ÿ‘‰๏ธ false

The String.endsWith method returns true if the string ends with the specified substring and false otherwise.

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

The String.slice() method can be passed negative indexes to count backward.

index.js
const str = 'bobbyhadz.com'; console.log(str.slice(0, -1)); // ๐Ÿ‘‰๏ธ bobbyhadz.co

Passing an end index parameter of -1 and string.length - 1 is the same.

We instruct the slice method to go up to, but not including the last character in the string.

The function checks if the string starts with a comma and if it does, it strips the leading and trailing commas.

index.js
function removeLeadingTrailingComma(str) { if (str.startsWith(',') && str.endsWith(',')) { return str.slice(1, -1); } if (str.startsWith(',')) { return str.slice(1); } if (str.endsWith(',')) { return str.slice(0, -1); } return str; }
The code for this article is available on GitHub

If the string starts with a comma but doesn't end with one, the function removes the leading comma.

If the string ends with a comma but doesn't start with one, the function removes the trailing comma.

If the string doesn't start with or end with a comma, the function returns the entire string without removing anything.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev