JavaScript(JS) string method - charat

www.i‮g‬iftidea.com

The charAt() method is a built-in method of the JavaScript String object. It returns the character at the specified index in a string.

Here's the syntax:

str.charAt(index)

where str is the string to get the character from, and index is the zero-based index of the character to retrieve.

Here's an example that shows how to use the charAt() method:

const myString = "hello world";
console.log(myString.charAt(1)); // "e"

In this example, we create a string myString with the value "hello world". We use the charAt() method to retrieve the character at index 1, which is "e". The resulting value is "e".

If the specified index is out of range, charAt() returns an empty string.

console.log(myString.charAt(100)); // ""

In this example, we try to retrieve the character at index 100, which is out of range for the length of the string. charAt() returns an empty string.

The charAt() method is a useful tool for retrieving individual characters from a string. It can be used in combination with other methods such as substring() to extract substrings from a string.