Skip to content

Instantly share code, notes, and snippets.

@ijy
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.
<!--
ALTERNATIVE SEARCH & REPLACE
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:choose>
<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:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$string" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- 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}" />
</xsl:call-template>
</xsl:variable>
<!-- Output -->
<xsl:value-of select="string-mod" />
<!-- Result: "This is a sample text : {I've been replaced} and {I've been replaced}" -->
@Azagh3l
Copy link

Azagh3l commented Aug 11, 2016

The output line is missing a $ and should be as follows to work correctly :

<!-- Output -->
<xsl:value-of select="$string-mod" />

@RudiKlassen-zz
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