JavaScript is a powerful programming language that is widely used in web development. One of the most important features of JavaScript is its ability to manipulate strings. Strings are a sequence of characters that are used to represent text. JavaScript provides a number of methods that can be used to search for specific characters or patterns within a string. These methods are collectively known as the JS String Search methods.
The JS String Search methods are used to search for specific characters or patterns within a string. These methods include:
indexOf()
: This method searches for a specified character or substring within a string and returns the index of the first occurrence.lastIndexOf()
: This method searches for a specified character or substring within a string and returns the index of the last occurrence.search()
: This method searches for a specified regular expression within a string and returns the index of the first occurrence.match()
: This method searches for a specified regular expression within a string and returns an array of all matches.replace()
: This method searches for a specified regular expression within a string and replaces the matches with a specified replacement string.Here are some examples of how to use the JS String Search methods:
indexOf()
The indexOf()
method searches for a specified character or substring within a string and returns the index of the first occurrence. If the character or substring is not found, it returns -1.
var str = "Hello, world!";
var index = str.indexOf("o");
console.log(index); // Output: 4
lastIndexOf()
The lastIndexOf()
method searches for a specified character or substring within a string and returns the index of the last occurrence. If the character or substring is not found, it returns -1.
var str = "Hello, world!";
var index = str.lastIndexOf("o");
console.log(index); // Output: 8
search()
The search()
method searches for a specified regular expression within a string and returns the index of the first occurrence. If the regular expression is not found, it returns -1.
var str = "Hello, world!";
var index = str.search(/o/);
console.log(index); // Output: 4
match()
The match()
method searches for a specified regular expression within a string and returns an array of all matches.
var str = "The quick brown fox jumps over the lazy dog.";
var matches = str.match(/the/gi);
console.log(matches); // Output: ["the", "the"]
replace()
The replace()
method searches for a specified regular expression within a string and replaces the matches with a specified replacement string.
var str = "The quick brown fox jumps over the lazy dog.";
var newStr = str.replace(/the/gi, "a");
console.log(newStr); // Output: "A quick brown fox jumps over a lazy dog."