Method 4:Using JavaScript str.length for index

Using string indexing, we can use string indexing to access the element of the array and use the length property of the string to access the last element index 

Example: This example uses string indexing to print the last character of the string.

Javascript
// Input string
let str = "w3wiki";

// Getting last character using str.length
let res = str[str.length-1];

// Display output
console.log(res);

Output
s

How to get the last character of a string in JavaScript ?

We are going to learn how can we get the last character of a string in JavaScript. we have given a string of size len, the task is to get the last character of a string using JavaScript.

There are several methods to solve this problem:

Table of Content

  • Method 1: Using charAt() Method
  • Method 2: Using str.slice() Method
  • Method 3: Using str.substr() Method
  • Method 4:Using JavaScript str.length for index
  • Method 5: Using String.at() method
  • Method 6: Using String.match() method
  • Method 7: Using Array.prototype.pop() Method

Similar Reads

Method 1: Using charAt() Method

In this approach, we will count the number of characters in a given string by using the str.length property. Since the indexing starts from 0 use str.charAt(str.length-1) to get the last character of the string....

Method 2: Using str.slice() Method

In this approach, we will use the string.slice() function and it will return the last character of the string....

Method 3: Using str.substr() Method

In this approach, we will use the str.substr method and it returns the specified number of characters from the specified index from the given string....

Method 4:Using JavaScript str.length for index

Using string indexing, we can use string indexing to access the element of the array and use the length property of the string to access the last element index...

Method 5: Using String.at() method

In this method, we can pass -1 for getting the last character of the string....

Method 6: Using String.match() method

In this method, we will use regular expression for getting the last character of the given string....

Method 7: Using Array.prototype.pop() Method

In this approach, we convert the string to an array, use the pop() method to remove and return the last element, which is the last character of the string....