Senthil Arasu
Senthil Arasu

Reputation: 293

Remove the word 'and' in XSLT using translate function

I would like to remove the word 'and' from a string using the translate function rather than using a replace .

for instance:

 <xsl:variable name="nme" select="translate(./Name/text(), ',:, '')" />

in addition to ",:" i would like to remove the word 'and' as well. Please suggest.

Upvotes: 4

Views: 4435

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

The translate function can't do this, it can only remove or replace single characters, not multi-character strings. Like so many things in XSLT 1.0 the escape route is a recursive template, the simplest version being:

<xsl:template name="removeWord">
  <xsl:param name="word" />
  <xsl:param name="text" />

  <xsl:choose>
    <xsl:when test="contains($text, $word)">
      <xsl:value-of select="substring-before($text, $word)" />
      <xsl:call-template name="removeWord">
        <xsl:with-param name="word" select="$word" />
        <xsl:with-param name="text" select="substring-after($text, $word)" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

And then call this template when you define the nme variable.

<xsl:variable name="nme">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="'and'" /><!-- note quotes-in-quotes -->
    <xsl:with-param name="text" select="translate(Name, ',:', '')" />
  </xsl:call-template>
</xsl:variable>

Here I'm using translate to remove the single characters and then passing the result to the template to remove "and".

Though as pointed out in the comments, it depends exactly what you mean by "word" - this will remove all occurrences of the string "and" including in the middle of other words, you might want to be more conservative, removing only " and" (space-and), for example.

To remove more than one word you simply call the template repeatedly, passing the result of one call as a parameter to the next

<xsl:variable name="noEdition">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="'Edition'" />
    <xsl:with-param name="text" select="translate(Name, ',:', '')" />
  </xsl:call-template>
</xsl:variable>

<xsl:variable name="nme">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="' and'" />
    <xsl:with-param name="text" select="$noEdition" />
  </xsl:call-template>
</xsl:variable>

Upvotes: 5

Related Questions