web analytics

XSLT Template: Implementing an index-of function

Options

codeling 1602 - 6666
@2016-01-08 11:33:06

The following XSLT template demostates how to implement a index-of function which returns the position of a string in another string. The function returns -1 if there is no instance of "searched string" in the string.

<xsl:template name="index-of">
    <xsl:param name="string"/>
    <xsl:param name="search"/>
    <xsl:variable name="result">
        <xsl:choose>
            <xsl:when test="contains($string,$search)">
                <xsl:variable name="string-before">
                    <xsl:value-of select="substring-before($string,$search)"/>
                </xsl:variable>
                <xsl:value-of select="1 + string-length($string-before)"/>
            </xsl:when>
            <xsl:otherwise>-1</xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:copy-of select="$result"/>
</xsl:template>

The following code snippet shows you how to use the above template:

<xsl:variable name="index">
    <xsl:call-template name="index-of">
        <xsl:with-param name="string" select="'Hello world !'" />
        <xsl:with-param name="search" select="'o'"/>
    </xsl:call-template>
</xsl:variable>
<xsl:value-of select="index"/>

Result

5

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com