SyntaxStudy
Sign Up
JavaScript String Methods: length, charAt, indexOf, includes
JavaScript Beginner 6 min read

String Methods: length, charAt, indexOf, includes

Core String Methods — Part 1

JavaScript strings come with a rich built-in API. The most frequently used utility methods let you inspect the length of a string, access individual characters, and search for substrings without writing any custom loop logic.

length

length is a property (not a method) that returns the number of UTF-16 code units in the string. For most everyday text this equals the number of characters, but emoji and certain Unicode symbols can be two code units long.

charAt and Bracket Notation

charAt(index) returns the character at the given zero-based index. Bracket notation (str[0]) works identically for most purposes, but charAt returns an empty string for out-of-range indices while bracket notation returns undefined.

indexOf and lastIndexOf

indexOf(searchValue) returns the first index at which searchValue is found, or -1 if it is absent. lastIndexOf searches from the end. Both accept an optional second argument specifying where to begin the search.

includes, startsWith, endsWith

These three methods return boolean values and are the most readable way to check for the presence or position of a substring. They are case-sensitive.

Example
const str = 'JavaScript is fun';
console.log(str.length);          // 17
console.log(str.charAt(0));       // J
console.log(str[4]);              // S
console.log(str.indexOf('is'));   // 11
console.log(str.lastIndexOf('a')); // 3
console.log(str.includes('fun')); // true
console.log(str.startsWith('Java')); // true
console.log(str.endsWith('fun'));    // true
console.log(str.indexOf('Python')); // -1
Pro Tip

Prefer includes() over indexOf() !== -1 when you only need to know whether a substring exists — it communicates intent far more clearly.