How do I remove non-alphanumeric characters from a string in XSL?
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
It's very easy. Just extend the range of your translate() call to cover the problem characters (characters that you use in the attribute, but that XML forbids for element names).
You can make your own using only XSLT 1.0: If only a trim is required, you can just implement it yourself like the following template. It calls itself recursively and strips away chars until the first and last char of the built-in XSLT function normalize-space() match the first and last chars of the remaining string.
Select the range that you need to remove non-alphanumeric characters from, and click Kutools > Text > Remove Characters. 2. Then a Delete Characters dialog box will appear, only check Non-alphanumeric option, and click the Ok button. Now all of the non-alphanumeric characters have been deleted from the text strings.
If you define non-alphanumeric as [^a-zA-Z0-9]
:
<xsl:value-of select="
translate(
string,
translate(
string,
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
''
),
''
)
" />
Note that this is for XSLT 1.0. In XSLT 2.0 you can work with regexes directly, using replace()
.
For XSLT 2.0 you can use replace()
as follows:
<xsl:value-of select="replace(<string>, '[^a-zA-Z0-9]', '')" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With