开发者

How to embed dynamic html safely in a dynamic javascript file so that it doesn't break the javascript

开发者 https://www.devze.com 2023-01-23 05:49 出处:网络
I need 开发者_如何学运维to build a javascript file on the fly and embed some html inside it, so that when run, thejavascript will be able to add the html to the DOM.

I need 开发者_如何学运维to build a javascript file on the fly and embed some html inside it, so that when run, the javascript will be able to add the html to the DOM.

I hava a javascript.js that I can interpolate using wicket. It contains:

var html = "${somehtml}"

document.write(html);

At the moment, if I replace the ${somehtml} with html that contains single quotes, it will obviously break the html.

I tried using URLEncoder.encode() and javascript unescape() but this broke the javascript.

I'm wondering if I can encode/decode to/from base64? Or is there a another solution?


First replace every backslash with two backslashes, then replace every quote with a backslash and a quote. Something like

var newstring = mystring.replace(/\\/g, "\\\\").replace(/"/g, '\\"');


Apache Commons provides a helper class called StringEscapeUtils. It can encode strings so that they can be safely embedded in javascript (ecmascript).


I doubt this is what you're looking for because you're building the js on the fly but embedded javascript files (*.ejs) allow you to load markup from an external file (with the option to pass custom data in too) rather than putting everything in quotes and looking generally messy.

It's at least useful for development, but I'd rather not have to send more files to the client.

http://embeddedjs.com/

<ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

versus

someVar += "<ul>";
for(var i=0; i<supplies.length; i++) {
    someVar += "<li>" + supplies[i] + "</li>";
}
someVar += "</ul>";
0

精彩评论

暂无评论...
验证码 换一张
取 消