indexof()

The indexof() function returns the index of the first occurrence of a specified substring within a string.

Syntax

indexof(STR, NEEDLE[, FROM_INDEX])

Parameters

STR
The string to search within.
NEEDLE
The substring to find within STR.
FROM_INDEX
The index position at which to start the search. Indices start at 0. A negative value is treated as 0.

Description

The indexof() function returns the index (32-bit integer) of the first occurrence of NEEDLE within STR. If NEEDLE is not found, the function returns -1.

If FROM_INDEX is specified, the search proceeds forward from that position.

If STR or NEEDLE is null, the function returns null. Non-string values are converted using toString() before processing.

Error codes

N/A

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Find the first occurrence of a path segment in a URI

    table limit=5 WEB_APACHE_SAMPLE | eval result = indexof(uri, "/") | fields uri, result
    | # result: 0 (when the URI starts with /)
    
  2. Find the second / in a URI using FROM_INDEX

    table limit=5 WEB_APACHE_SAMPLE | eval result = indexof(uri, "/", 1) | fields uri, result
    
  3. Search for a substring that is not present

    table limit=5 WEB_APACHE_SAMPLE | eval result = indexof(method, "?") | fields method, result
    | # result: -1
    
  4. NULL input

    json "{'val': null}" | eval result = indexof(val, "world")
    | # result: null
    

Compatibility

The indexof() function is available since before Sonar 4.0.