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

substring() : Extract Substring


On this page

Summary

Extract a portion of a string starting at a specified position.

Signature

substring(str, start, length?)

Parameters

Parameter Type Required Description
str String Yes The source string
start Number Yes Zero-based starting position
length Number No Number of characters to extract (omit for rest of string)

Returns

Type: String

The extracted substring.


Examples

Extract First N Characters

<p>Short Name: ...</p>

Data:

doc.Params["model"] = new {
    fullName = "Christopher Anderson"
};

Output:

<p>Short Name: Christophe...</p>

Extract from Position to End

<p>Last Name: </p>

Data:

doc.Params["model"] = new {
    fullName = "John Doe"
};

Output:

<p>Last Name: Doe</p>

Truncate Long Text


  <div class="article">
    <h3></h3>
    
      <p>... <a href="#">Read more</a></p>
    
      <p></p>
    
  </div>

Data:

doc.Params["model"] = new {
    articles = new[] {
        new { title = "Article 1", content = "Short content." },
        new { title = "Article 2", content = "This is a very long article content that exceeds one hundred characters and should be truncated with a read more link." }
    }
};

Output:

<div class="article">
  <h3>Article 1</h3>
  <p>Short content.</p>
</div>
<div class="article">
  <h3>Article 2</h3>
  <p>This is a very long article content that exceeds one hundred characters and should be truncated with... <a href="#">Read more</a></p>
</div>

Extract Middle Portion

<p>Code: </p>

Data:

doc.Params["model"] = new {
    fullCode = "PRE-12345678-SUF"
};

Output:

<p>Code: 12345678</p>

First Initial

<p>Initial: </p>

Data:

doc.Params["model"] = new {
    name = "alice"
};

Output:

<p>Initial: A</p>

Notes

  • Start position is zero-based (0 = first character)
  • If length is omitted, extracts to end of string
  • Throws exception if start position exceeds string length
  • If length exceeds remaining characters, returns rest of string
  • For finding position first, use indexOf() then substring()
  • Negative indices are not supported

See Also