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.

  

 

 

 

back to top