How to Extract a Specific Letter from a String in JavaScript?

Estimated read time 1 min read

To extract a specific letter from a string in JavaScript, you can use the String.charAt() method or square bracket notation. Here are two examples:

Using String.charAt() method:

const string = "Hello, world!";
const letter = string.charAt(1);
console.log(letter); // Output: "e"

Here’s what the String.charAt() method does:

  • The argument (1) is the index of the character to extract.
  • The method returns the character at the specified index as a new string.

In this example, letter will contain the character at index 1, which is “e”.

Using square bracket notation:

const string = "Hello, world!";
const letter = string[1];
console.log(letter); // Output: "e"

Here’s what square bracket notation does:

  • The argument (1) is the index of the character to extract.
  • This syntax is a shorthand way to access a character in a string.

In this example, letter will contain the character at index 1, which is “e”. Note that not all JavaScript engines support square bracket notation for strings, but it is supported in all modern browsers and Node.js.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply