Skip to content

Instantly share code, notes, and snippets.

Created September 15, 2013 16:56
Show Gist options
  • Save ijy/6572481 to your computer and use it in GitHub Desktop.
Save ijy/6572481 to your computer and use it in GitHub Desktop.
Alternative search and replace template for XSLT 1.0.
string: The text to be evaluated
replace: The character or string to look for in the above string
with: What to replace it with
Slightly more long winded approach if that's how you prefer to roll.
<xsl:template name="string-replace">
<xsl:param name="string" />
<xsl:param name="replace" />
<xsl:param name="with" />
<xsl:when test="contains($string, $replace)">
<xsl:value-of select="substring-before($string, $replace)" />
<xsl:value-of select="$with" />
<xsl:call-template name="string-replace">
<xsl:with-param name="string" select="substring-after($string,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="with" select="$with" />
<xsl:value-of select="$string" />
<!-- Example template call -->
<xsl:variable name="string-mod">
<xsl:call-template name="string-replace">
<xsl:with-param name="string" select="'This is a sample text : {replace} and {replace}'" />
<xsl:with-param name="replace" select="'{replace}'" />
<xsl:with-param name="with" select="'{I've been replaced}" />
<!-- Output -->
<xsl:value-of select="string-mod" />
<!-- Result: "This is a sample text : {I've been replaced} and {I've been replaced}" -->
Copy link

RudiKlassen-zz commented Jan 20, 2017

The with param tag is missing a [']. It should be: <xsl:with-param name="with" select="'{I've been replaced}'" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment