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
Data:
doc.Params["model"] = new {
fullName = "Christopher Anderson"
};
Output:
<p>Short Name: Christophe...</p>
Extract from Position to End
Data:
doc.Params["model"] = new {
fullName = "John Doe"
};
Output:
<p>Last Name: Doe</p>
Truncate Long Text
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
Data:
doc.Params["model"] = new {
fullCode = "PRE-12345678-SUF"
};
Output:
<p>Code: 12345678</p>
First Initial
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()thensubstring() - Negative indices are not supported