Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape a JavaScript string in Play 2.0 view?

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?

like image 640
Ben Dilts Avatar asked Mar 16 '12 19:03

Ben Dilts


People also ask

How do you escape a string in JavaScript?

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.

Do I need to escape in JavaScript 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.

How do I escape JavaScript in HTML?

JavaScript escape() The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.


1 Answers

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"
like image 108
Julien Richard-Foy Avatar answered Jan 03 '23 17:01

Julien Richard-Foy