get nth character of string javascript
- Published
- Reading time
- 1 min read
- Length
- 179 words
On this page
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: oMethod 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: oMethod 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: oThese 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();