Recipe2.2.Finding the Position of a Substring


Recipe 2.2. Finding the Position of a Substring

Problem

You want to find 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 string preceding it plus 1. If you are certain that the target string contains the substring, then you can simply use string-length(substring-before($value, $substr))+1. However, in general, you need a way to handle the case in which the substring is not present. Here, zero is chosen as an indication of this case, but you can use another value such as -1 or NaN.




XSLT Cookbook
XSLT Cookbook: Solutions and Examples for XML and XSLT Developers, 2nd Edition
ISBN: 0596009747
EAN: 2147483647
Year: 2003
Pages: 208
Authors: Sal Mangano

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net