A trailing comma leaves a comma after the last element at the end of a list (it can be an element in an Array literal), a property in an Object literal, or a function parameter.
And if you use an old browser that only supports ECMAScript 3 or earlier (IE8), the program will give an error when leaving extra commas at the end of the params.
Trailing commas are only helpful with lists on multiple lines, so you don’t need to leave any commas when the list is short on the same line.
With function parameter lists, trailing commas were only accepted in ES2017. If the JS engine does not yet support it, and when run directly, it will cause a syntax error. So it is safer if your code is compiled through Babel and preset-env.
Therefore, you should still avoid using trailing commas in function parameters. When writing functions with too long parameter lists, you should use object literals to collect the list of parameters.
Using replace() method
The replace() method is used to replace all old characters or strings with new characters or strings.
In this way, we will use the replace method of the string to be able to search and replace the leading and Trailing Comma. Let’s see the code below and watch the input and output strings change.
var string = ",John, Kevin, Nick,"; var result = string.replace(/(^,)|(,$)/g, ""); console.log(result);
John, Kevin, Nick
Then we replace them with the empty string and we can get the result of this topic.
Using split() & trim() & join() method
This would be a way to use more string-handling methods, but it seems more manageable for the coder to understand. Firstly, we will use the
split() method to split the string into an array of separate words separated by “,” then use the
trim() method to remove the spaces before and after the substring.
var string = ",John, Kevin, Nick,"; var result= string.split(',').map(e => e.trim()).filter(e => e).join(', ') console.log(result);
John, Kevin, Nick
Finally, we use the
join() method to join the substrings in the array, and we get the new string to remove the leading and trailing comma. I hope these methods are helpful to you.
Maybe you are interested:
Name of the university: PTIT