How to useBracket Notation in Javascript

In this approach we are using bracket notation like str[0] accesses the first character and str[str.length – 1] accesses the last character of a string.

Syntax:

objectname['propertyname']; // Bracket notation

Example: In this example we are using the above-explained approach.

Javascript
let str = "JavaScript";
let firstChar = str[0];
let lastChar = str[str.length - 1];

console.log("First character:", firstChar);
console.log("Last character:", lastChar);

Output
First character: J
Last character: t

How to Find the First and Last Character of a String in JavaScript ?

In this article, we are going to learn about finding the first and last character of a string in JavaScript. The first character of a string is its initial symbol, while the last character is the final symbol at the end of the string.

Strings are sequences of characters. Here we have some common methods to find the first and last character of a string by using JavaScript.

Example:

Input: w3wiki;
Output: first character : G , Last character : s

There are several methods that can be used to find the first and last character of a string in JavaScript, which are listed below:

Table of Content

  • Using charAt() Method
  • Using Bracket Notation
  • Using Substring() Method
  • Using String.slice() Method
  • Using ES6 Destructuring


We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using charAt() Method

In this approach, we are using the charAt() method, to access the first and last characters of a string by specifying indices 0 and length – 1, respectively....

Approach 2: Using Bracket Notation

In this approach we are using bracket notation like str[0] accesses the first character and str[str.length – 1] accesses the last character of a string....

Approach 3: Using Substring() Method

Using substring() extracts characters from start to end indices. For first character, use str.substring(0, 1), for last character, use str.substring(str.length – 1)....

Approach 4: Using String.slice() Method

In this approach we are using slice() method on a string extracts characters. For first character, use str.slice(0, 1), for last character, use str.slice(-1)....

Approach 5: Using ES6 Destructuring

With ES6 destructuring, you can easily extract the first and last characters of a string in a concise and readable way....