Overview
JavaScript string search allows you to find the index of a substring within a string. This can be useful for a variety of tasks, such as finding the first occurrence of a character in a string, removing all occurrences of a word from a string, or replacing all occurrences of a string with another string.
Methods
There are two main methods for performing string search in JavaScript:
IndexOf() – This method returns the index of the first occurrence of a substring within a string. If the substring is not found, the method returns -1.
LastIndexOf() – This method returns the index of the last occurrence of a substring within a string. If the substring is not found, the method returns -1.
Examples
The following examples demonstrate how to use the indexOf() and lastIndexOf() methods to perform string search in JavaScript:
// indexOf()const string = "Hello, world!";
const index = string.indexOf("world");
console.log(index);
// 7// lastIndexOf()
const index = string.lastIndexOf("world");
console.log(index);
// 7
Advanced Search
In addition to the indexOf() and lastIndexOf() methods, there are a number of other methods that can be used for more advanced string search in JavaScript. These methods include:
Match() – This method returns an array of all occurrences of a substring within a string. If the substring is not found, the method returns null.
Search() – This method returns the index of the first occurrence of a regular expression within a string. If the regular expression is not found, the method returns -1.
Replace() – This method replaces all occurrences of a substring within a string with another string.
Examples
The following examples demonstrate how to use the match(), search(), and replace() methods to perform more advanced string search in JavaScript:
// match()const string = "Hello, world!";
const matches = string.match("world");
console.log(matches);
// [“world”]// search()
const string = "Hello, world!";
const index = string.search(/world/);
console.log(index);
// 7// replace()
const string = "Hello, world!";
const newString = string.replace("world", "universe");
console.log(newString);
// “Hello, universe!”
Conclusion
JavaScript string search is a powerful tool that can be used for a variety of tasks. By understanding the different methods available, you can perform string search efficiently and effectively.