XSL Tip – Getting Last Index of a Character Using Recursion

Est. Reading Time: 2 minute

There is a way to get the last index of a character using a recursion in XSL 1.0. The method below goes through the string taking off pieces until its gets to the last character that you define.

This particular example is getting the filename of a URL.

<!-- define a lastIndexOf named template -->
<xsl:template name="lastIndexOf">
   <!-- declare that it takes two parameters - the string and the char -->
   <xsl:param name="string" />
   <xsl:param name="char" />
      <!-- if the string contains the character... -->
      <xsl:when test="contains($string, $char)">
         <!-- call the template recursively... -->
         <xsl:call-template name="lastIndexOf">
            <!-- with the string being the string after the character -->
            <xsl:with-param name="string" select="substring-after($string, $char)" />
            <!-- and the character being the same as before -->
            <xsl:with-param name="char" select="$char" />
      <!-- otherwise, return the value of the string -->
      <xsl:otherwise><xsl:value-of select="$string" /></xsl:otherwise>

To get the filename of a URL held in the URL child of the current node, 
you can call this template like:

<xsl:call-template name="lastIndexOf">
   <xsl:with-param name="string" select="URL" />
   <xsl:with-param name="char" select="/" />

Source: www.sourceware.org