Reputation: 158
A few days back I had asked a similar question for replacing spaces in XSLT , but now I am facing another issue within the same code.
Previously Asked: So I have to export data from our application, now for doing that I wrote XML code and while exporting certain fields need to be formatted for which i am using XSLT. Now the issue here is in my SQL SERVER database I have a contact number field, some of the number are in the format 1234567890 while some have spaces 123 456 7890. So now when I am using the below mentioned xslt code, everything is working as expected if the field has spaces but messes up when it does not have spaces. I know I can make changes in the database directly but that will not be permanent solution. If anyone could provide some guidance it would be great. Solution was as follows:
<xsl:variable name="phone" select="translate(D_PHONE, ' ', '')" />
<xsl:value-of select="concat('(', substring($phone, 1, 3), ') ', substring($phone, 4, 3), '-', substring($phone, 7, 4))" />
But now the issue is some of the fields are coming back as 123-456-7890 with dashes instead of spaces and this solution does fail because of that. Is there a replace tag where I can basically mention all the characters that I want to replace in the field and then format them as previously ?
Thank you guys in advance.
Upvotes: 0
Views: 1556
Reputation: 117102
As mentioned in the comments, you could add all unwanted characters to the translate()
function that translates them to an empty string (IOW, removes them).
For example, this removes both spaces and hyphens:
<xsl:variable name="phone" select="translate(D_PHONE, ' -', '')" />
Alternatively, you could define the variable so that only digits are retained:
<xsl:variable name="phone" select="translate(D_PHONE, translate(D_PHONE, '0123456789', ''), '')"/>
Upvotes: 1