String Replacement with XSLT

While working with SharePoint, I found that I sometimes need to replace strings with some characters or strings, for example, replacing "&" with "&", or replacing "_x0020_" with " ". This is a useful template to do so. I got this template from here.

   1:      <!-- here is the template that does the replacement -->
   2:      <xsl:template name="replaceCharsInString">
   3:        <xsl:param name="stringIn"/>
   4:        <xsl:param name="charsIn"/>
   5:        <xsl:param name="charsOut"/>
   6:        <xsl:choose>
   7:          <xsl:when test="contains($stringIn,$charsIn)">
   8:            <xsl:value-of select="concat(substring-before($stringIn,$charsIn),$charsOut)"/>
   9:            <xsl:call-template name="replaceCharsInString">
  10:              <xsl:with-param name="stringIn" select="substring-after($stringIn,$charsIn)"/>
  11:              <xsl:with-param name="charsIn" select="$charsIn"/>
  12:              <xsl:with-param name="charsOut" select="$charsOut"/>
  13:            </xsl:call-template>
  14:          </xsl:when>
  15:          <xsl:otherwise>
  16:            <xsl:value-of select="$stringIn"/>
  17:          </xsl:otherwise>
  18:        </xsl:choose>
  19:      </xsl:template>

And here's how you'll call it.

   1:  <!-- pretend this is in a template -->
   2:    <xsl:variable name="myString" select="'This%20is%20Test'"/>
   3:    <xsl:variable name="myNewString">
   4:      <xsl:call-template name="replaceCharsInString">
   5:        <xsl:with-param name="stringIn" select="string($myString)"/>
   6:        <xsl:with-param name="charsIn" select="'%20'"/>
   7:        <xsl:with-param name="charsOut" select="' '"/>
   8:      </xsl:call-template>
   9:    </xsl:variable>
  10:    <!-- $myNewString is a result tree fragment, which should be OK. -->
  11:    <!-- If you really need a string object, do this: -->
  12:    <xsl:variable name="myNewRealString" select="string($myNewString)"/>

And there you have it. Very useful indeed.