Wednesday, 13 November 2024

Accessing Characters of a String using Indexing in JavaScript

In JavaScript, you can access individual characters in a string using index notation. This is done by specifying the position of the character you want to access within square brackets ([]), following the string variable or the string literal. The index of the first character is 0, the second character is 1, and so on.

Example 1: Accessing the first character

let greeting = "Hello";
let firstChar = greeting[0];
console.log(firstChar); // Output: "H"

 

Here, greeting[0] accesses the first character of the string "Hello", which is "H".

 

Example 2: Accessing the last character.

let greeting = "Hello";
let lastChar = greeting[greeting.length - 1];
console.log(lastChar); // Output: "o"

Example 3: Accessing a character in the middle.

let word = "JavaScript";
let charAtIndex4 = word[4];
console.log(charAtIndex4); // Output: "S"

Here, word[4] accesses the character at index 4 in the string "JavaScript", which is "S".

 

Example 4: Accessing characters in a string literal directly

console.log("Hello"[2]); // Output: "l"

You can also access characters directly from a string literal. In this case, "Hello"[2] returns the character "e".

 

If you try to access a character at an index that doesn't exist (e.g., an index greater than the length of the string), JavaScript will return undefined.

 

let word = "Hi";

console.log(word[10]); // Output: undefined

 

accessCharsInString.js

let greeting = "Hello";
let firstChar = greeting[0];
let lastChar = greeting[greeting.length - 1];

console.log(`greeting : ${greeting}, firstChar : ${firstChar}`);
console.log(`greeting : ${greeting}, lastChar : ${lastChar}`);

let word = "JavaScript";
let charAtIndex4 = word[4];
console.log(`word : ${word}, charAtIndex4 : ${charAtIndex4}`);

console.log(`Hello[2] : ${"Hello"[2]}`); 

word = "Hi";
console.log(`word : ${word}, word[10] : ${word[10]}`);

Output

greeting : Hello, firstChar : H
greeting : Hello, lastChar : o
word : JavaScript, charAtIndex4 : S
Hello[2] : l
word : Hi, word[10] : undefined


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment