In JavaScript, you can search for substrings within a string using various methods. Here are some commonly used techniques for string searching:
The indexOf() method 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
console.log(str.indexOf("foo")); // Output: -1
The lastIndexOf() method returns the index of the last occurrence of a specified substring within a string. If the substring is not found, it returns -1.
let str = "Hello, world!";
console.log(str.lastIndexOf("o")); // Output: 8
console.log(str.lastIndexOf("foo")); // Output: -1
You can use regular expressions to perform more advanced string searches. The search() method returns the index of the first match of a regular expression within a string, while the match() method returns an array of all matches.
let str = "Hello, world!";
console.log(str.search(/world/)); // Output: 7
console.log(str.match(/o/g)); // Output: ["o", "o"]
The includes() method checks whether a string contains a specified substring and returns true or false.
let str = "Hello, world!";
console.log(str.includes("world")); // Output: true
console.log(str.includes("foo")); // Output: false
The startsWith() method checks whether a string starts with the specified prefix, while the endsWith() method checks whether a string ends with the specified suffix.
let str = "Hello, world!";
console.log(str.startsWith("Hello")); // Output: true
console.log(str.endsWith("world!")); // Output: true
These are some of the techniques you can use to search for substrings within a string in JavaScript. Depending on your specific requirements, you can choose the appropriate method or combination of methods to perform string searching efficiently.