XML technologies / XSLT / XSLT Kochbuch / Strings / Finding the position of a substring
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
You want to determine the index of a substring within a string, rather than the text before or after the substring.
Solution
XSLT 1.0
<xsl:template name="string-index-of">
<xsl:param name="input"/>
<xsl:param name="substr"/>
<xsl:choose>
<xsl:when test="contains($input, $substr)">
<xsl:value-of select="string-length(substring-before($input, $substr))+1"/>
</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</xsl:template>XSLT 2.0
<xsl:function name="ckbk:string-index-of">
<xsl:param name="input"/>
<xsl:param name="substr"/>
<xsl:sequence select="if (contains($input, $substr)) then string-length(substring-before($input, $substr))+1 else 0"/>
</xsl:function>Discussion
The position of a substring within another string is simply the length of the preceding string plus 1. If you are sure the target string contains the substring, you can simply use string-length(substring-before($value, $substr))+1. In general, however, you need a way to handle a missing substring. Here, 0 was chosen to indicate this case, but you can choose another value, such as -1 or NaN.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from "XSLT Kochbuch" is subject to the same terms as the printed edition: the work and all its parts are protected by copyright. All rights are reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de