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

replace() : Replace Text

Replace all occurrences of a substring with another string.


On this page

Signature

replace(str, find, replacement)

Parameters

Parameter Type Required Description
str String Yes The source string
find String Yes The substring to find
replacement String Yes The replacement text

Returns

Type: String

A new string with all occurrences replaced.


Examples

Simple Replacement

<p>{{replace(model.text, 'old', 'new')}}</p>

Data:

doc.Params["model"] = new {
    text = "The old car was sold to an old friend."
};

Output:

<p>The new car was snew to an new friend.</p>

Remove Characters

<p>Phone: {{replace(model.phone -  '')}}</p>

Data:

doc.Params["model"] = new {
    phone = "555-123-4567"
};

Output:

<p>Phone: 5551234567</p>

Format Display

<p>{{replace(model.code, '_', ' ')}}</p>

Data:

doc.Params["model"] = new {
    code = "PREMIUM_CUSTOMER_DISCOUNT"
};

Output:

<p>PREMIUM CUSTOMER DISCOUNT</p>

Sanitize Input

{{#each model.items}}
  <p>{{replace(replace(this.name, '<', '&lt;'), '>', '&gt;')}}</p>
{{/each}}

Template Variable Replacement

<p>{{replace(replace(model.template, '{name}', model.name), '{date}', model.date)}}</p>

Data:

doc.Params["model"] = new {
    template = "Hello {name}, today is {date}",
    name = "John",
    date = "March 15"
};

Output:

<p>Hello John, today is March 15</p>

Notes

  • Replaces all occurrences (not just first)
  • Case-sensitive matching
  • Returns original string if find text not found
  • To remove text, use empty string as replacement
  • For pattern-based replacement, use regexSwap()
  • For single character replacement, more efficient than regex

See Also