JavaScript String Methods
String methods are built-in functions that help you work with strings. JavaScript provides dozens of methods for searching, extracting, replacing, transforming, and analyzing text. These methods make string manipulation powerful and convenient.
Common String Methods
The length property (not a method) returns the number of characters in a string. While technically a property rather than a method, it's essential for working with strings. Access it without parentheses: string.length. Length is useful for validation (checking minimum/maximum lengths), looping through characters, or determining if a string is empty (length === 0).
The toUpperCase() method converts all characters in a string to uppercase letters and returns the new string. The original string remains unchanged because strings are immutable. This method is useful for case-insensitive comparisons, formatting output, or normalizing user input. For example, comparing "hello".toUpperCase() === "HELLO".toUpperCase() ensures case doesn't affect the comparison.
The toLowerCase() method converts all characters to lowercase letters and returns the new string. Like toUpperCase(), it doesn't modify the original. This method is commonly used for case-insensitive searches, email address normalization (emails are case-insensitive), or standardizing user input before processing or storing it.
The indexOf() method finds the first occurrence of a specified substring within a string and returns its index position. If the substring isn't found, it returns -1. The search is case-sensitive. You can optionally provide a second parameter to specify where to start searching. This method is useful for checking if a string contains certain text or finding where it appears.
The slice() method extracts a portion of a string and returns it as a new string without modifying the original. It takes two parameters: the start index (inclusive) and the end index (exclusive). Negative indices count from the end of the string. If you omit the end index, slice extracts to the end of the string. This is one of the most versatile methods for string extraction.
The replace() method searches for a specified value (string or regular expression) and replaces it with a new value, returning the new string. By default, replace() only replaces the first occurrence. To replace all occurrences, use a regular expression with the global flag (/pattern/g) or the replaceAll() method. The original string remains unchanged.
The trim() method removes whitespace from both ends of a string and returns the new string. Whitespace includes spaces, tabs, and newlines. This is extremely useful for cleaning user input—users often accidentally add spaces before or after text. Related methods include trimStart() (removes whitespace from the beginning) and trimEnd() (removes from the end).
let text = " Hello World ";
// Length
console.log(text.length); // 15
// Case conversion
console.log(text.toUpperCase()); // " HELLO WORLD "
console.log(text.toLowerCase()); // " hello world "
// Trim whitespace
console.log(text.trim()); // "Hello World"
// indexOf
console.log(text.indexOf("World")); // 8
// slice
console.log(text.slice(2, 7)); // "Hello"
// replace
let newText = text.replace("World", "JavaScript");
console.log(newText); // " Hello JavaScript "
More String Methods
The split() method divides a string into an array of substrings based on a specified separator. The separator can be a string or regular expression. For example, "a,b,c".split(",") returns ["a", "b", "c"]. If you use an empty string as the separator, split() divides the string into individual characters. This method is invaluable for parsing CSV data, splitting sentences into words, or breaking strings into processable parts.
The concat() method joins two or more strings together and returns the concatenated result. While concat() works, the + operator or template literals are more commonly used for concatenation in modern JavaScript. Multiple strings can be concatenated: str1.concat(str2, str3, str4). The original strings remain unchanged, and a new combined string is returned.
The charAt() method returns the character at a specified index position in a string. It's similar to bracket notation (string[index]) but charAt() returns an empty string for invalid indices while bracket notation returns undefined. For example, "Hello".charAt(1) returns "e". While bracket notation is more common in modern code, charAt() remains useful and explicit.
The includes() method checks whether a string contains a specified substring, returning true or false. This method is case-sensitive. You can optionally provide a second parameter to specify where to start searching. includes() is more readable than checking if indexOf() !== -1. It's perfect for validation, filtering, or conditional logic based on string content.
The startsWith() method checks if a string begins with a specified substring, returning true or false. The check is case-sensitive. You can provide an optional second parameter to specify the position to start checking from. This method is cleaner and more expressive than using slice() or substring() combined with equality checks for checking string prefixes.
The endsWith() method checks if a string ends with a specified substring, returning true or false. Like startsWith(), it's case-sensitive. You can optionally specify the length of the string to consider (useful for checking endings at specific positions). This method is perfect for file extension checking, URL validation, or any scenario where the string's ending matters.
let str = "Hello World JavaScript";
// split
let words = str.split(" ");
console.log(words); // ["Hello", "World", "JavaScript"]
// concat
let greeting = "Hello".concat(" ", "World");
console.log(greeting); // "Hello World"
// charAt
console.log(str.charAt(0)); // "H"
// includes
console.log(str.includes("World")); // true
// startsWith
console.log(str.startsWith("Hello")); // true
// endsWith
console.log(str.endsWith("Script")); // true