2

I am using JavaScript something like this:

<script>
  <xsl:for-each select = '/request/alldata'>

    var l_allDataValue   = '<xsl:value-of select="." />';
    var l_dataArray = l_allDataValue.split('!~');

    callFunction(l_dataArray);

  </xsl:for-each>
</script>

But if there is a apostrophe ' in /request/alldata it will break the JavaScript because the following expression is enclosed in apostrophes:

'<xsl:value-of select="." />'

But it works if I replace this with either of the following...

"<xsl:value-of select="." />" OR "<xsl:value-of select='.' />"

Now I know the apostrophe ' is clashing with the JavaScript code, but which solution will work in all browsers?

1 Answer 1

2

You can use '<xsl:value-of select="." />' but you will need to escape all single quote apostrophes in the <alldata> by prepending a slash like this \'

You can use "<xsl:value-of select="." />" or "<xsl:value-of select='.' />" but if there is a chance the <alldata> will contain a double quote, then you will need to escape those as well, like this \"

If you want to use the first, then this will escape the single quote:

<xsl:template name="escapeSingleQuotes">
  <xsl:param name="txt"/>

  <xsl:variable name="backSlashSingleQuote">&#92;&#39;</xsl:variable>
  <xsl:variable name="singleQuote">&#39;</xsl:variable>

  <xsl:choose>
    <xsl:when test="string-length($txt) = 0">
      <!-- empty string - do nothing -->
    </xsl:when>

    <xsl:when test="contains($txt, $singleQuote)">
      <xsl:value-of disable-output-escaping="yes" 
                    select="concat(substring-before($txt, $singleQuote), $backSlashSingleQuote)"/>

      <xsl:call-template name="escapeSingleQuotes">
        <xsl:with-param name="txt" select="substring-after($txt, $singleQuote)"/>
      </xsl:call-template>
    </xsl:when>

    <xsl:otherwise>
      <xsl:value-of disable-output-escaping="yes" select="$txt"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

You could use in your code like this:

var l_allDataValue = '<xsl:call-template name="escapeSingleQuotes">
                        <xsl:with-param name="txt" select="."/>
                      </xsl:call-template>'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.