The String object's indexOf() method
The String object's 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.
Prerequisites
This tutorial assumes that you're familiar with:
Syntaxstring.indexOf(searchString[, position])
ParameterssearchString:
The string to search for within the original string
Case-sensitive search
position (optional):
string.indexOf(searchString[, position])
searchString:
The string to search for within the original string
Case-sensitive search
The position in the string to begin searching from
Default is 0 (start of string)
If position is negative, the search starts at the beginning
If position >= string length, returns -1
Return value
Returns a number representing:
The index of the first occurrence of searchString
-1 if the searchString is not found
ExamplesExample 1: Basic substring searching
In the code below, the function indexOfEx1()
demonstrates basic usage of indexOf()
.
function indexOfEx1() {
let str = "Hello World";
// Find position of "World"
Logger.log(str.indexOf("World")); // 6
// Case-sensitive search
Logger.log(str.indexOf("world")); // -1
// Find a single character
Logger.log(str.indexOf("o")); // 4
// Substring not found
Logger.log(str.indexOf("xyz")); // -1
}
Output
6
-1
4
-1
Example 2: Using the position parameter
In the code below, the function indexOfEx2()
shows how to use the optional starting position.
function indexOfEx2() {
let str = "Hello World, Hello Apps Script";
// Find first "Hello"
Logger.log(str.indexOf("Hello")); // 0
// Find second "Hello" by starting after first one
Logger.log(str.indexOf("Hello", 1)); // 13
// Start searching from middle of string
Logger.log(str.indexOf("Hello", 15)); // -1
// Negative position starts from beginning
Logger.log(str.indexOf("Hello", -5)); // 0
}
Output
0
13
-1
0
Example 3: Common practical applications
In the code below, the function indexOfEx3()
demonstrates typical use cases for indexOf()
.
function indexOfEx3() {
// Check if string contains substring
let email = "user@example.com";
let hasAtSign = email.indexOf("@") !== -1;
Logger.log("Is valid email format: " + hasAtSign);
// Extract domain from email
let domainStart = email.indexOf("@") + 1;
let domain = email.slice(domainStart);
Logger.log("Domain: " + domain);
// Check file extension
let filename = "document.pdf";
let isDotPresent = filename.indexOf(".") !== -1;
Logger.log("Has file extension: " + isDotPresent);
}
Output
Is valid email format: true
Domain: example.com
Has file extension: true
Example 4: Finding all occurrences
In the code below, the function indexOfEx4()
shows how to find all occurrences of a substring.
function indexOfEx4() {
let str = "The quick brown fox jumps over the lazy fox";
let searchTerm = "fox";
let positions = [];
let pos = 0;
// Find all occurrences of "fox"
while (true) {
pos = str.indexOf(searchTerm, pos);
if (pos === -1) break;
positions.push(pos);
pos += 1; // Move to next position
}
Logger.log("Found '" + searchTerm + "' at positions: " + positions);
}
Output
Found 'fox' at positions: 16, 40
Important Characteristics of indexOf()
Here are key behaviors you should understand when using indexOf()
:
Case Sensitivity: The method distinguishes between uppercase and lowercase letters. For example,
"Hello".indexOf("hello")
returns-1
because"hello"
with a lowercase'h'
is considered different from"Hello"
with an uppercase'H'
.First Occurrence Only: The method stops searching after finding the first match. If you need to find the last occurrence of a substring, use
lastIndexOf()
instead. For example,"Hello Hello".indexOf("Hello")
returns0
, not6
.Not Found Indicator: When
indexOf()
returns-1
, it means the substring wasn't found. This makes it perfect for existence checks:
if (str.indexOf("search") !== -1) {
// String contains "search"
}
Works Well with Other String Methods: You can combine
indexOf()
with other string methods for text processing. For example:
let email = "user@example.com";
let atPosition = email.indexOf("@");
let domain = email.slice(atPosition + 1); // extracts "example.com"
Common Use Cases
The indexOf()
method is frequently used in text processing tasks. Here are some common applications:
Validation: Check if a string contains specific characters or substrings.
Parsing: Find the position of delimiters or markers in structured text.
Text extraction: Locate starting points for substring extraction.
File processing: Check file names or extensions.
Email validation: Basic email format checking.
URL processing: Find components within URLs.
Related Methods
lastIndexOf()
: Finds the last occurrence of a substringincludes()
: Returns true/false for substring existencesearch()
: Similar to indexOf() but supports regular expressions
Conclusion
In this tutorial, you learned how to use the indexOf()
method to find substrings within strings in Apps Script. This method is essential for string searching, validation, and text processing tasks. While indexOf()
is simple to use, it's powerful when combined with other string methods or used in loops to process text systematically. Remember that indexOf()
is case-sensitive and only finds the first occurrence of a substring.