Get substring before last instance of a character.

eshurak
eshurak used Ask the Experts™
on
Using XSLT version 1.0 I'd like to be able to return all text in string before a certain character.

I've been using:
<xsl:variable name="Url" select="substring-before($linkData, ',')" />

Which works fine with the string only has one comma, but when there are more the one commas I need it to get every thing before the last comma.  Is this possible.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Information Architect
Top Expert 2006
Commented:
you need to do this recursively
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:variable name="linkData" select="/linkdata"/>
    <xsl:template match="/">
        <xsl:variable name="Url">
            <xsl:call-template name="all-before-last-comma">
                <xsl:with-param name="str" select="$linkData"/>
            </xsl:call-template>
        </xsl:variable>
    <xsl:value-of select="$Url"/>
    </xsl:template>
<xsl:template name="all-before-last-comma">
    <xsl:param name="str"/>
        <xsl:if test="contains($str, ',')">
            <xsl:value-of select="substring-before($str, ',')"/>
            <xsl:if test="contains(substring-after($str, ','), ',')">
                <xsl:text>,</xsl:text>
            </xsl:if>
            <xsl:call-template name="all-before-last-comma">
                <xsl:with-param name="str" select="substring-after($str, ',')"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>
</xsl:stylesheet>

Open in new window

Gertone (Geert Bormans)Information Architect
Top Expert 2006

Commented:
The above uses this input
<linkdata>123,123,456,1,</linkdata>

you can easily integrate it with your code of course

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial