trim.text
Prev | General Library Templates | Next

## trim.text

trim.text — Trim leading and trailing whitespace from a text node

## Description

Given a text node, this function trims leading and trailing whitespace from it and returns the trimmed contents.

      <xsl:template name="trim.text">
        <xsl:param name="contents" select="."></xsl:param>
        <xsl:variable name="contents-left-trimmed">
          <xsl:call-template name="trim-left">
            <xsl:with-param name="contents" select="$contents"></xsl:with-param>
          </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="contents-trimmed">
          <xsl:call-template name="trim-right">
            <xsl:with-param name="contents" select="$contents-left-trimmed"></xsl:with-param>
          </xsl:call-template>
        </xsl:variable>
        <xsl:value-of select="$contents-trimmed"></xsl:value-of>
      </xsl:template>

      <xsl:template name="trim-left">
        <xsl:param name="contents"></xsl:param>
        <xsl:choose>
          <xsl:when test="starts-with($contents,'
    ') or                       starts-with($contents,'
    ') or                       starts-with($contents,' ') or                       starts-with($contents,'	')">
            <xsl:call-template name="trim-left">
              <xsl:with-param name="contents" select="substring($contents, 2)"></xsl:with-param>
            </xsl:call-template>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$contents"></xsl:value-of>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:template>

      <xsl:template name="trim-right">
        <xsl:param name="contents"></xsl:param>
        <xsl:variable name="last-char">
          <xsl:value-of select="substring($contents, string-length($contents), 1)"></xsl:value-of>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test="($last-char = '
    ') or                       ($last-char = '
    ') or                       ($last-char = ' ') or                       ($last-char = '	')">
            <xsl:call-template name="trim-right">
              <xsl:with-param name="contents" select="substring($contents, 1, string-length($contents) - 1)"></xsl:with-param>
            </xsl:call-template>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$contents"></xsl:value-of>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:template>

Prev | Up | Next
comment-escape-string.recursive | Home | str.tokenize.keep.delimiters