types.String.indexof
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
substr | string | the substring to look for; must not be empty |
start | number | byte index to start searching from; defaults to 0 optional |
... | any | not 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
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 substringSee also
contains | Returns whether str contains substr. |
slice | Returns the bytes of str from start up to, but not including, end. |
split | Splits str into an array of strings. |
| string | class index |