How to remove the last character of a string in Javascript

How to remove the last character of a string in Javascript

ยท

1 min read

Hello Friends , hope your doing well ๐Ÿ˜€

As a budding learner and writer I like to share everything I discover, and today I'll share with you how to get the last character of a string :

  • We can do it in many ways but the method that I love the most is using str.slice() method
const string = "Dicko0";
console.log(string.slice(0, -1)); // "Dicko"

Apart from the method mentioned above , we can also use these methods :

const string = "Dicko0";
console.log(string.substr(0, string.length - 1)); // "Dicko"
console.log(string.substring(0, string.length - 1)); // "Dicko"

The last method that we can also use is String.prototype.replace()

As define on MDN , The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

In that case we'll use regex pattern to grab the end of the string and then replace it .

const string = "Javascripts";
console.log(string.replace(/.$/, ""));  // "Javascript"

And that's all for this little article , thanks for your reading .

And don't hesitate to suggest anything that can improve the article and point out any mistakes (typos , coding ,etc ...) . Don't forget like it ๐Ÿ˜€ .