Removing Specific Characters from a String
Problem
You want to strip certain characters (e.g., whitespace) from a string.
Solution
Use translate with an empty replace string. For
example, the following code can strip whitespace from a string:
translate($input," 	
&xd;", "")
Discussion
translate( )
is a versatile string function that is
often used to compensate for missing string-processing capabilities
in XSLT. Here you use the fact that translate( )
will not copy characters in the input string that are in the
from string but do not have a corresponding
character in the to string.
You can also use translate to remove all but a
specific set of characters from a string. For example, the following
code removes all non-numeric characters from a string:
translate($string,
translate($string,'0123456789',''),'')The inner translate( ) removes all characters of
interest (e.g., numbers) to obtain a from string
for the outer translate( ), which removes these
non-numeric characters from the original string.
Sometimes you do not want to remove all occurrences of whitespace,
but instead want to remove leading, trailing, and redundant internal
whitespace. XPath has a built-in function, normalize-space( ),
which does just that. If you ever
needed to normalize based on characters other than spaces, then you
might use the following code (where C is the character you want to
normalize):
translate(normalize-space(translate($input,"C "," C")),"C "," C")
However, this transformation won’t work ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access