简体   繁体   中英

How to deal with sigle quote in javascript in jsp page?

onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"

${viewWPMasterGrid.name} retutrns me a string(for eg WPWINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. How to deal with problem?

When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. Just as when a dynamic String is put inside a HTML page, it's HTML-escaped.

Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. You could create a very simple EL function to do that straight from the JSP.

Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal.

It looks like you could split the second parameter out into its own variable first. If I have understood your question correctly.

var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";

使用'${viewWPMasterGrid.name.replaceAll("'", "\\'")}'

尝试这个,

var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM