Quirrel4.41.0

types.String.indexof

Method on every string
pure string.indexof(substr: string, [start: number], ...): any

Returns the byte index of the first occurrence of substr in str.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

substrstringthe substring to look for; must not be empty
startnumberbyte index to start searching from; defaults to 0 optional
...anynot a real parameter; see Notes repeats

Return value

The byte index of the first match at or after start, or null if there is no match - not -1. start must be within [0, str.len()); a negative or out-of-range start also gives null rather than wrapping the way a negative index does for types.String.slice.

The search is a raw byte search (it calls strstr), so it also finds a match that is only part of a multi-byte character, and finds substr at the byte offset where its bytes occur, not at a character position.

Errors

Throws empty substring when substr is "".

Notes

Takes 1 or 2 arguments: start is optional. A third argument is silently ignored.

types.String.contains runs the exact same scan but returns a bool instead of an index or null.

Example

examples/types/string/indexof.nut
println("\"hello\".indexof(\"l\") =", "hello".indexof("l"))
println("\"hello\".indexof(\"l\", 3) =", "hello".indexof("l", 3))

// not found is null, not -1.
let r = "hello".indexof("z")
println("\"hello\".indexof(\"z\") == null =", r == null)

try { "hello".indexof("") } catch (e) println("\"hello\".indexof(\"\") throws:", e)
Output:
"hello".indexof("l") = 2
"hello".indexof("l", 3) = 3
"hello".indexof("z") == null = true
"hello".indexof("") throws: empty substring

See also

containsReturns whether str contains substr.
sliceReturns the bytes of str from start up to, but not including, end.
splitSplits str into an array of strings.
stringclass index