Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Functions operating on strings (7/15) >

Extracting substring with substring-before() and substring-after() functions

The function substring-before() returns a part of the string provided as the first argument which occurs before the first occurrence of the substring given in the second argument. The function substring-after() returns the part following the first occurrence of the substring. If the substring does not occur in the original string and empty string is returned.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/aaa">
                  <xxx>
                        <xsl:value-of  select="substring-before(.,':')"/>
                  </xxx>
                  <yyy>
                        <xsl:value-of  select="substring-after(.,':|:')"/>
                  </yyy>
                  <zzz>
                        <xsl:value-of  select="substring-after(.,',')"/>
                  </zzz>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>AAA:|:BBB:|:CCC</aaa>
Output

      <xxx>AAA</xxx>
      <yyy>BBB:|:CCC</yyy>
      <zzz/>


Previous chapter: Arithmetics
Next chapter: Transforming strings with regular expressions
Previous page: Extracting substrings with substring function
Next page: Transforming strings to lowercase and uppercase