Skip to main content Link Search Menu Expand Document Toggle dark mode Copy Code (external link)

trim() : Remove Whitespace

Remove leading and trailing whitespace from a string.


On this page

Signature

trim(str)

Parameters

Parameter Type Required Description
str String Yes The string to trim

Returns

Type: String

The string with leading and trailing whitespace removed.


Examples

Remove Extra Spaces

<p>"{{trim(model.text)}}"</p>

Data:

doc.Params["model"] = new {
    text = "  Hello World  "
};

Output:

<p>"Hello World"</p>

Clean User Input

{{#each model.names}}
  <li>{{trim(this)}}</li>
{{/each}}

Data:

doc.Params["model"] = new {
    names = new[] { "  John  ", " Jane ", "Bob   " }
};

Output:

<li>John</li>
<li>Jane</li>
<li>Bob</li>

Normalize for Comparison

{{#if trim(model.status) == 'active'}}
  <span class="active">Active</span>
{{/if}}

Data:

doc.Params["model"] = new {
    status = " active "
};

Output:

<span class="active">Active</span>

Clean Multi-Line Text

<p>{{trim(model.description)}}</p>

Data:

doc.Params["model"] = new {
    description = @"
        This is a description
        with extra whitespace
    "
};

Output:

<p>This is a description
        with extra whitespace</p>

Notes

  • Removes spaces, tabs, newlines from both ends
  • Does not affect whitespace in the middle of string
  • Returns original string if no whitespace at ends
  • For trailing whitespace only, use trimEnd()
  • Does not modify the original value
  • Useful for cleaning user input and data

See Also