Yogesh Chauhan's Blog

How to remove trailing characters from a string using JavaScript?

in JavaScript on May 16, 2021

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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Learn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHPIs there a CSS parent selector?CSSKilling A Project Part 2: Who should make the decision to kill a project?MiscellaneousHow to Create a Backup From Any Database in SQL?SQL/MySQLHow to position an image on top of another image using CSS?CSS3 Ways we can create URLSearchParams Objects in JavaScriptJavaScript