get the last character of a string in JavaScript

Question

Answers ( 1 )

    0
    2024-01-16T19:15:03+00:00

    To answer this question, there are several methods in JavaScript to get the last character of a string:

    1. Using String Length: The simplest way is to use the length of the string to access the last character.

      var str = "Hello World";
      var lastChar = str[str.length - 1];
      console.log(lastChar); // Outputs: 'd'
      

      Here, str.length - 1 gives the index of the last character in the string.

    2. Using charAt() Method: You can use the charAt() method, which returns the character at a specified index.

      var str = "Hello World";
      var lastChar = str.charAt(str.length - 1);
      console.log(lastChar); // Outputs: 'd'
      

      This is similar to the first method but uses a string method for better readability.

    3. Using slice() Method: The slice() method extracts a section of a string and returns it as a new string. To get the last character, you can pass -1 as the argument.

      var str = "Hello World";
      var lastChar = str.slice(-1);
      console.log(lastChar); // Outputs: 'd'
      

      This method is useful as it is very readable and straightforward.

    4. Using substr() Method: Another method is using substr() with -1 as the argument, which will return the last character.

      var str = "Hello World";
      var lastChar = str.substr(-1);
      console.log(lastChar); // Outputs: 'd'
      

      Note: substr() is considered a legacy function and may be deprecated in the future, so it's better to use slice().

    5. Using substring() Method: You can also use substring() method, but it requires the length of the string.

      var str = "Hello World";
      var lastChar = str.substring(str.length - 1);
      console.log(lastChar); // Outputs: 'd'
      

      This method is similar to slice() but is less preferred for getting the last character.

    Each of these methods is valid for getting the last character of a string in JavaScript, and you can choose based on your preference for readability and the specific requirements of your code.

Leave an answer