My question is similar to Finding last occurence
However i need to output the whole string, just before the last occurence of the delimiter. So the out put in the example should be ABC_12345
Must be XSLT 1.0
Example: substring -before ('14/9', '/') - This statement returns the result as '14'. Example: Substring-before('pebble - ball','-') // this returns a value pebble that is before 'hypen'. The function returns an empty string while in the case of the absence of a second-string contained in the first string.
substring-before() Function — Returns the substring of the first argument before the first occurrence of the second argument in the first argument. If the second argument does not occur in the first argument, the substring-before() function returns an empty string.
Substring is primarily used to return a section of a string or truncating a string with the help of the length provided. XSLT is incorporated with XPath while manipulating strings of text when XSLT access. The Substring function takes a string as an argument with the numbers one or two and an optional length.
XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.
Look at the substring-before-last
template I implemented for another question.
Removing the last characters in an XSLT string
It seems to be exactly what you need.
This is essentially the same solution, but in order to preserve the intermediate delimiters in the result, the following three lines must be added:
<xsl:if test="contains(substring-after($pText, $pDelim), $pDelim)">
<xsl:value-of select="$pDelim"/>
</xsl:if>
The whole transformation now becomes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="s" select="'ABC_12345_Q-10'"/>
<xsl:template match="/">
<xsl:call-template name="stripLast">
<xsl:with-param name="pText" select="$s"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="stripLast">
<xsl:param name="pText"/>
<xsl:param name="pDelim" select="'_'"/>
<xsl:if test="contains($pText, $pDelim)">
<xsl:value-of select="substring-before($pText, $pDelim)"/>
<xsl:if test="contains(substring-after($pText, $pDelim), $pDelim)">
<xsl:value-of select="$pDelim"/>
</xsl:if>
<xsl:call-template name="stripLast">
<xsl:with-param name="pText" select=
"substring-after($pText, $pDelim)"/>
<xsl:with-param name="pDelim" select="$pDelim"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on any XML document (not used), the wanted, correct result is produced:
ABC_12345
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