Different ways to get the last character from a string in JavaScript

Different ways to get the last character from a string in JavaScript:

In this post, we will learn different ways to get the last character from a string in JavaScript.

Strings are used to store a series of characters. Each character of a string can be accessed by its index. The index starts at 0 and ends at length - 1, where length is the length of the string. For the first character, it is 0 and for the last character, it is length - 1.

Method 1: By using charAt:

JavaScript strings has one inbuilt method called charAt. This method takes the index value and returns the character at that index.

It is defined as like below:

charAt(position)

Where, position is the index position of the character.

To get the last character of a string, we can pass length - 1 to this method parameter. length is the string length and we can get it by reading the .length property of a string.

Below is the complete program:

let given_str = 'hello world';

console.log(given_str.charAt(given_str.length - 1))

If you run this program, it will print d.

Method 2: By using slice:

slice method is used to extract a part of a string in JavaScript. We can use this method to get the last string character.slice is defined as like below:

slice(begin, end)

where, begin is the index to start the slicing and end is the index to end the slicing. Both are zero based index.

end is an optional value. If this is not provided, slice will take it as the end of the string.

We can also provide a negative value to these values. If we provide any negative value, it will add that value to the length of the string. For example, if we provide -2, it will be string length - 2.

To get the last character, we can pass -1 as the parameter to slice. It will return the last character of that string.

Below is the complete program:

let given_str = 'hello world';

console.log(given_str.slice(-1))

It will print d.

Method 3: By using substr():

substr is another method we can use to get the last character of a string. This method is used to get one substring from a string. It is defined as like below:

substr(start, length)

Here, start is the first character index, i.e. the character to start extracting the substring. length is the size of the substring we need or it is the number of characters to include in the final substring.

length is an optional value.

We can also provide a negative value to start. For negative values, it starts from the end of the string.

To get the last character using substr, we can pass -1 as start and no value for length.

let given_str = 'hello world';

console.log(given_str.substr(-1))

It will print d.

You might also like: