XSLT: conditionally add a substring modification

I have a function that adds zero width characters. It doesn’t quite work the way I want. How to get it to add a zero space character every 15 characters only if it does not contain normal space?

<xsl:template match="text()[parent::d:entry]">
    <xsl:call-template name="intersperse-with-zero-spaces">
        <xsl:with-param name="str" select="."/>
        <xsl:with-param name="max_length" select="number(15)"/>
    </xsl:call-template>
</xsl:template>
<xsl:template name="intersperse-with-zero-spaces">
        <xsl:param name="str"/>
        <xsl:param name="max_length"/>
        <xsl:variable name="ret">
            <xsl:value-of select="substring($str, 1, $max_length)"/>
            <xsl:if test="string-length($str) &gt; $max_length">
                <xsl:value-of select="'&#x200b;'"/>
                <xsl:call-template name="intersperse-with-zero-spaces">
                    <xsl:with-param name="str" select="substring($str, $max_length + 1)"/>
                    <xsl:with-param name="max_length" select="$max_length"/>
                </xsl:call-template>
            </xsl:if>
        </xsl:variable>
        <xsl:value-of select="$ret"/>
    </xsl:template>
+3
source share
1 answer

Some tips. Firstly:

<xsl:template match="d:entry/text()">

better than

<xsl:template match="text()[parent::d:entry]">

And then:

<xsl:template name="intersperse-with-zero-spaces">
  <xsl:param name="str"/>
  <xsl:param name="max_length"/>

  <!-- your variable "ret" is not necessary at all -->

  <xsl:variable name="head" select="substring($str, 1, $max_length)" />
  <xsl:variable name="tail" select="substring($str, $max_length + 1)" />

  <xsl:value-of select="$head"/>

  <!-- the empty string evaluates to false -->
  <xsl:if test="$tail">
    <!-- there no space present when translate() returns the same string
         and the $tail does not begin with a space, either  -->
    <xsl:if test="
      string-length(translate($head, ' ', '')) = string-length($head)
      and not(substring($tail, 1, 1) = ' ')
    ">
      <xsl:text>&#x200b;</xsl:text>
    </xsl:if>
    <xsl:call-template name="intersperse-with-zero-spaces">
      <xsl:with-param name="str"        select="$tail"/>
      <xsl:with-param name="max_length" select="$max_length"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

In addition, I would call a variable $interval, not $max_length. But this is purely cosmetic.

+3
source

Source: https://habr.com/ru/post/1785034/


All Articles