Sometimes, I need to render a JavaScript variable using EL in a JSF page.
E.g.
<script>var foo = '#{bean.foo}';</script>
or
<h:xxx ... onclick="foo('#{bean.foo}')" />
This fails with a JS syntax error when the EL expression evaluates to a string containing JS special characters such as apostrophe and newline. How do I escape it?
Have you tried
\'#{_selectedItem.item.webName}\',
?You can use Apache Commons Lang 3.x
StringEscapeUtils#escapeEcmaScript()
method for this in EL.First create a
/WEB-INF/functions.taglib.xml
which look like this:Then register it in
/WEB-INF/web.xml
as follows:Then you can use it as follows:
Alternatively, if you happen to already use the JSF utility library OmniFaces, then you can also just use its builtin
of:escapeJS()
function: