In JavaScript, you can search for substrings within a string using various methods. Here are some common approaches:
indexOf(searchValue[, fromIndex]): Returns the index of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.
let str = "Hello, world!";
console.log(str.indexOf("world")); // Output: 7
lastIndexOf(searchValue[, fromIndex]): Returns the index of the last occurrence of a specified substring within a string, searching backward from the specified index.
let str = "Hello, world!";
console.log(str.lastIndexOf("o")); // Output: 8
includes(searchString[, position]): Checks whether a string contains a specified substring. It returns true
if the substring is found, otherwise false
.
let str = "Hello, world!";
console.log(str.includes("world")); // Output: true
startsWith(searchString[, position]): Checks whether a string starts with a specified substring. It returns true
if the string starts with the specified substring, otherwise false
.
let str = "Hello, world!";
console.log(str.startsWith("Hello")); // Output: true
endsWith(searchString[, length]): Checks whether a string ends with a specified substring. It returns true
if the string ends with the specified substring, otherwise false
.
let str = "Hello, world!";
console.log(str.endsWith("world!")); // Output: true
RegExp: Regular expressions can be used for more advanced string searches, allowing for pattern matching and more complex search criteria.
let str = "Hello, world!";
let pattern = /world/g;
console.log(str.match(pattern)); // Output: ["world"]
Each of these methods provides different ways to search for substrings within a string, offering flexibility based on your specific search requirements.