Is there an easy way to escape a string to be used as a JavaScript string in a view in Play 2.0? For example, here's a simple view that creates a link with a confirm box in onclick:
@(text:String,link:Call,message:String)
<a href="@link" onclick="return confirm('@message');">@text</a>
That will fail if there are newlines or single quotes in message. What's the best way to do this?
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
TL;DR there's no need for crazy hacks like string concatenation or char literal escapes — just escape it as such: var snaphtml = '<\/script>'; Also, note that this is only necessary for inline scripts.
JavaScript escape() The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.
You can use Apache Commons Lang:
@(text:String, link:Call, message:String)
@import org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript
<a href="@link" onclick="return confirm('@escapeEcmaScript(message)');">@text</a>
You can avoid the explicit import in the template by adding it to your project/Build.scala
file:
templatesImport += "org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript"
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