XML technologies / XSLT / XSLT Cookbook / Strings / Remove specific characters from a string

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to remove specific characters, such as whitespace, from a string.

Solution

XSLT 1.0

Use translate with an empty replacement string. This removes whitespace:

translate($input," 	
&xd;", "")

XSLT 2.0

In XSLT 2.0, translate() is normally the best choice too. Some removals are more naturally expressed using regular expressions and the new replace() function:

(: \s erfasst alle Whitespace-Zeichen :)

replace($input,"\s","")

Discussion

translate() is a versatile function compensating for XSLT 1.0’s limited string processing. Here it exploits the fact that translate() does not copy input characters present in string from without a corresponding character in string to.

Use translate() to remove everything except a chosen character set. This removes nonnumeric characters:

translate($string, translate($string,'0123456789',''),'')

The inner translate() removes the wanted characters, such as digits, to obtain string from for the outer translate(), which removes those unwanted characters from the original.

Sometimes only leading, trailing and redundant internal whitespace should be removed. XPath provides built-in function normalize-space() for that. To normalize other characters, use this code, where C is the character to normalize:

translate(normalize-space(translate($input,"C "," C")),"C "," C")

This fails with whitespace other than spaces: tabs (#x9), newlines (#xA) and carriage returns (#xD). The code swaps spaces and the target character, normalizes spaces and swaps back. Other remaining whitespace is also normalized, probably unintentionally. Non-whitespace normalization is rare anyway. Here the technique removes extra - characters:

<xsl:template match="/">
  <xsl:variable name="input" select=" '---dies --ist-- die Methode zum Normalisieren von Nicht-Whitespace---' "/>
  <xsl:value-of select="translate(normalize-space(translate($input,'- ',' -')),'- ',' -')"/>
</xsl:template>

The result is:

dies -ist- die Methode zum Normalisieren von Nicht-Whitespace

XSLT 2.0

A more powerful method uses XSLT 2.0 function replace() with regular expressions. Here replace() normalizes non-whitespace without the 1.0 solution’s potential problems:

<xsl:template match="/">
  <xsl:variable name="input" select=" '---dies --ist-- die Methode zum Normalisieren von Nicht-Whitespace---' "/>
  <xsl:value-of select="replace(replace($input,'-+','-'),'^-|-$','')"/>
</xsl:template>

This calls replace() twice: the inner call replaces repeated - with a single -, and the outer call removes leading and trailing - characters.

  

 

 

 

back to top