String Search & Indexing
indexOf(substring, fromIndex?)
→ Returns the first occurrence index of a substring (-1
if not found).
lastIndexOf(substring, fromIndex?)
→ Returns the last occurrence index of a substring.
let str = "hello world hello";
console.log(str.indexOf("hello")); // 0 (first occurrence)
console.log(str.indexOf("hello", 5)); // 12 (search after index 5)
console.log(str.lastIndexOf("hello")); // 12 (last occurrence)
includes(substring)
→ Checks if a string contains a substring.
console.log("hello".includes("ll")); // true
startsWith(searchString)
/ endsWith(searchString)
→ Checks if a string starts or ends with a substring.
console.log("hello".startsWith("he")); // true
console.log("hello.js".endsWith(".js")); // true
Extracting & Modifying Strings
charAt(index)
→ Returns the character at a specific index.
let str = "Hello";
console.log(str.charAt(1)); // "e"
substring(start, end?)
→ Extracts part of a string (swaps start
and end
if start > end
).
console.log("JavaScript".substring(4, 10)); // "Script"
console.log("JavaScript".substring(10, 4)); // "Script" (arguments swapped)
slice(start, end?)
→ Extracts part of a string (supports negative indexes).
console.log("JavaScript".slice(-6)); // "Script"
console.log("JavaScript".slice(10, 4)); // "" (empty, as arguments are not swapped)
split(separator, limit?)
→ Splits a string into an array based on a separator.
let str = "apple,banana,grape";
console.log(str.split(",")); // ["apple", "banana", "grape"]
Case Transformation
toLowerCase()
→ Converts the string to lowercase.
toUpperCase()
→ Converts the string to uppercase.