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.
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.