0

In my xpage I create client side global variables in the following way:

<xp:scriptBlock>
<xp:this.value><![CDATA[var news_message = '#{javascript:return utilityBean.readLatestNews()}';
var news_lcation = '#{javascript:return sessionScope.get("location")}';
var news_title = '#{javascript:return sessionScope.get("title")}';
</xp:scriptBlock>

On the web page the variable can be as followed:

<script type="text/javascript">
var news_message= '<h4>NEWS</h4><p>Jane's puppies are not for sale</p>';
var news_location = 'top';
var news_title = 'Breaking news';
</script>

The single quote in Jane's puppies break the JS code.

The error message I get: Uncaught SyntaxError: Unexpected identifier 's' Uncaught ReferenceError: news_title is not defined

What can I do (server side or client side) to prevent this break of code?

Malin
  • 697
  • 5
  • 21
  • 1
    Use double quotes instead? This will break your code again though if your values contain a double quote, but this could easily be handled by escaping them with a back slash – Oliver Busse Feb 23 '23 at 13:27
  • 2
    Encode the single quote as \x27? https://stackoverflow.com/a/12473598/785061 – Per Henrik Lausten Feb 23 '23 at 13:27
  • I've never used them in xpages but [backticks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) are good when you're using a combination of single and double quotes – Adam Feb 27 '23 at 08:48

1 Answers1

0

Have you tried the StringEscapeUtils class in apache commons? e.g.

public static String escapeJS( final String input )
{
  return StringEscapeUtils.escapeEcmaScript( input );
}

will probably do the trick.

Patrick Kwinten
  • 1,988
  • 2
  • 14
  • 26