Removing one or more characters from a string is required when you append commas or spaces while joining bunch of strings.
There are multiple ways to remove the trailing characters from JavaScript.
using Substring() method
We can use the substring() method to extract characters from a string.
It takes two arguments, start and end for the substring you want. It does NOT include the end character.
This is how we can use substring() method to remove the trailing character(s):
Remove one character:
let blog = "YogeshChauhan.com,";
blog = blog.substring(0, blog.length - 1);
console.log(blog);
//YogeshChauhan.com
Remove multiple characters:
let blog = "YogeshChauhan.com, =";
blog = blog.substring(0, blog.length - 3);
console.log(blog);
//YogeshChauhan.com
using slice() method
We can use slice method to remove trailing characters from a string and the syntax is way cleaner.
Just like Array.from, slice method creates a copy of an array and returns it, basically taking an array as an argument and returning it with updated contents.
This is how we can remove last character from a string:
let blog = "YogeshChauhan.com,";
blog = blog.slice(0, -1);
console.log(blog);
//YogeshChauhan.com
This is how we can remove multiple characters:
let blog = "YogeshChauhan.com, =";
blog = blog.slice(0, -3);
console.log(blog);
//YogeshChauhan.com
examples slice special characters string substring trim