get nth character of string javascript

Get nth character of string javascript

Getting the nth character of a string in JavaScript can be done in multiple ways. Here are some of the ways:

Method 1: Using the charAt() method

The charAt() method is used to return the character at a specified index position in a string.


const str = "Hello World";
const n = 4;
const char = str.charAt(n);
console.log(char); // Output: o

Method 2: Using the bracket notation

The bracket notation can also be used to access a specific character at a given index position in a string.


const str = "Hello World";
const n = 4;
const char = str[n];
console.log(char); // Output: o

Method 3: Using the slice() method

The slice() method can be used to extract a portion of a string, starting from a specified index position.


const str = "Hello World";
const n = 4;
const char = str.slice(n, n+1);
console.log(char); // Output: o

These are some of the ways to get the nth character of a string in JavaScript. Choose the one that suits your needs best.

hljs.initHighlightingOnLoad();

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe