Remove last character of a string in javascript

In this programming tutorial we will learn how to remove last character of a string in javascript. It can be easily done by using some built-in javascript functions. I will discuss two methods to achieve the goal. Let's have a look over the code snippet given below.
Remove last character of a string in javascript
Method 1
var myString="Hello World!";
// newString will contain Hello World!
var newString = myString.substring(0, myString.length-1);
In the above method, we have a string 'hello world!', the newString subtract the string, take the character range from the first to the second last character of a string, and we will get the new string newString 'hello world'.
Method 2
var myString="Hello World!";
var newString = myString.slice(0, -1);// newString contains Hello World!
In the above method we are using the javascript built-in function slice(). Using slice() we can extract any part of the string . This function needs two parameters p1 and p2. Value of p1 indicates the starting position of the sub string and value of p2 gives the length of the sub string. The first position (left side) of the main string is known as 0 position of the string. Say for example we want sub string of length 5 characters from left side of the main string so here we have to use slice(0,5) . In our example we don't want to get the last character of a string that's why we use slice(0,-1). If we want to remove last two characters then definitely we will use slice(0,-2).

So that's it. This is the way to remove last character of a string in javascript.
I love your feedback.

0 comments: