Skip to main content Link Search Menu Expand Document (external link)

indexOf() : Find Substring Position


On this page

Summary

Find the first occurrence position of a substring within a string.

Signature

indexOf(str, search)

Parameters

Parameter Type Required Description
str String Yes The string to search in
search String Yes The substring to find

Returns

Type: Integer

The zero-based index of the first occurrence, or -1 if not found.


Examples

Check if Found


  <p>Email format detected</p>

  <p>Not an email</p>

Data:

doc.Params["model"] = new {
    text = "user@example.com"
};

Output:

<p>Email format detected</p>

Extract After Position

<p>Domain: </p>

Data:

doc.Params["model"] = new {
    email = "john@company.com"
};

Output:

<p>Domain: company.com</p>

Split on First Occurrence

<p>First part: </p>
<p>Second part: </p>

Data:

doc.Params["model"] = new {
    text = "apple, orange, banana"
};

Output:

<p>First part: apple</p>
<p>Second part: orange, banana</p>

Conditional Based on Position


  
    <p>Code with separator: </p>
  
    <p>Simple code: </p>
  

Data:

doc.Params["model"] = new {
    items = new[] {
        new { code = "ABC-123" },
        new { code = "XYZ789" }
    }
};

Output:

<p>Code with separator: ABC-123</p>
<p>Simple code: XYZ789</p>

Notes

  • Returns zero-based index (0 = first character)
  • Returns -1 if substring not found
  • Case-sensitive search
  • Returns index of first occurrence only
  • For case-insensitive search, use with toLower()
  • Commonly used with substring() for text extraction
  • For existence check only, use contains()

See Also