In JavaScript, strings are fundamental data types used to represent textual data. Searching within strings is a crucial operation for various tasks, from extracting information to validating user input. This chapter delves into the built-in methods and advanced techniques for searching JavaScript strings.
Returns: The index of the first occurrence of searchValue
within the string, or -1
if not found.
Parameters:
searchValue
: The string or regular expression you’re searching for.
fromIndex
(optional): The index at which to begin the search. Defaults to 0 (beginning of the string).
let str = "Hello, world!";
// Find the index of "world"
let index = str.indexOf("world");
console.log(index); // Output: 7
// Find the index of "o" starting from index 4
index = str.indexOf("o", 4);
console.log(index); // Output: 4
searchValue
within the string, or -1
if not found.searchValue
: The string or regular expression you’re searching for.fromIndex
(optional): The index at which to begin the search backward. Defaults to the string length (searching from the end).
let str = "Mississippi";
// Find the last index of "s"
let index = str.lastIndexOf("s");
console.log(index); // Output: 9
// Find the last index of "ss" starting from index 5
index = str.lastIndexOf("ss", 5);
console.log(index); // Output: 4
Both indexOf
and lastIndexOf
are case-sensitive. To perform a case-insensitive search, you can convert the string or searchValue
to lowercase before searching:
let str = "Hello, World!";
let index = str.toLowerCase().indexOf("world");
console.log(index); // Output: 7 (case-insensitive)
You can search for a single character (represented as a string of length 1) using these methods:
let str = "JavaScript";
let index = str.indexOf("J");
console.log(index); // Output: 0
index = str.lastIndexOf("t");
console.log(index); // Output: 10
These methods return only the first or last occurrence. To find all occurrences, you can use a loop or recursion:
function findAllOccurrences(str, searchValue) {
let occurrences = [];
let index = str.indexOf(searchValue);
while (index !== -1) {
occurrences.push(index);
index = str.indexOf(searchValue, index + 1); // Start from next index
}
return occurrences;
}
let str = "The rain in Spain falls mainly on the plain";
let allIndexes = findAllOccurrences(str, "ain");
console.log(allIndexes); // Output: [2, 18, 31]
regexp
within the string, or -1
if not found.regexp
: A regular expression object representing the pattern you’re searching for.
let str = "JavaScript 1.0";
let regexp = /\d+/; // Matches one or more digits
let index = str.search(regexp);
console.log(index); // Output: 11
Regular expressions offer powerful pattern matching capabilities. We’ll explore them further in the next section.
true
if searchValue
is found within the string, false
otherwise.searchValue
: The string you’re searching for.fromIndex
(optional): The index at which to begin the search. Defaults to 0.
let str = "JavaScript is awesome!";
let result = str.includes("Java"); // Case-sensitive
console.log(result); // Output: true
result = str.includes("script", 8); // Search from index 8
console.log(result); // Output: true (case-sensitive)
true
if the string starts with searchValue
, false
otherwise.searchValue
: The string you’re searching for.fromIndex
(optional): The index at which to begin the comparison. Defaults to 0.
let str = "Hello, world!";
let result = str.startsWith("Hello");
console.log(result); // Output: true
result = str.startsWith("world", 7); // Check from index 7
console.log(result); // Output: false
true
if the string ends with searchValue
, false
otherwise.searchValue
: The string you’re searching for.fromIndex
(optional): The index at which to begin the comparison. The search goes backward from this index (default is the string length).
let str = "JavaScript is awesome!";
let result = str.endsWith("awesome!");
console.log(result); // Output: true
result = str.endsWith("Script", str.length - 1); // Check from second-last character
console.log(result); // Output: false (case-sensitive)
We’ve covered creating regular expressions and common metacharacters. Let’s explore more advanced concepts:
Use \number
(where number
is the capturing group number) to refer to previously captured groups in the pattern
let str = "John (123) 456-7890";
let regexp = /\((\d{3})\) (\d{3})-(\d{4})/; // Capture area codes, exchange, and subscriber number
let match = str.match(regexp);
if (match) {
console.log("Area code:", match[1]); // Output: Area code: 123
console.log("Exchange:", match[2]); // Output: Exchange: 456
console.log("Subscriber number:", match[3]); // Output: Subscriber number: 7890
}
Assertions are zero-width matches that don’t consume any characters in the string but influence the matching process.
^
: Matches the beginning of the string or the beginning of a line in multiline mode (m
flag).$
: Matches the end of the string or the end of a line in multiline mode.\b
: Matches a word boundary (position between a word character and a non-word character or vice versa).
let str = "JavaScript: The language";
let regexp = /\bJava\w+/; // Matches "JavaScript" (not "Java")
let match = str.match(regexp);
if (match) {
console.log("Matched:", match[0]);
} else {
console.log("No match");
}
You can use inline modifiers like +?
, *+
, or ?=
within capturing groups to control the quantity of matches within the group.
let str = "aabccccdd";
let regexp = /a(b){2,4}c/g; // Matches "abbc", "abbbc", and "abcccc"
let matches = str.match(regexp);
console.log(matches); // Output: ["abbc", "abbbc", "abcccc"]
JavaScript regular expressions support Unicode characters. Consider using the u
flag for case-folding and other Unicode-aware behaviors.
By mastering basic and advanced string search methods in JavaScript, you can effectively extract information, validate user input, and perform various text processing tasks. This chapter has equipped you with a solid foundation in searching strings, empowering you to tackle more complex scenarios. Remember to consult the official JavaScript documentation for in-depth details Happy coding !❤️