简体   繁体   English

Javascript:需要替换HTML代码中存储为字符串的对象

[英]Javascript: Need to replace an object in an HTML code which is stored as a string

I am working on a website that shows different APIs we provide. 我正在一个显示我们提供的不同API的网站上工作。 It showcases the example code and preview for each API and a button to open code in plunker. 它展示了示例代码和每个API的预览以及一个在plunker中打开代码的按钮。 Since we have 100s of examples, we are not creating plunker for every example, but opening a new tab " https://plnkr.co/edit/?p=preview " and appending the corresponding html code into it. 由于我们有100多个示例,因此我们不会为每个示例都创建plunker,而是打开一个新标签“ https://plnkr.co/edit/?p=preview ”并将相应的html代码附加到其中。

Problem: 问题:

I have a total HTML document as a string in a javascript variable. 我在javascript变量中有一个完整的HTML文档作为字符串。

var html = "`<DOCTYPE html><html>....<body><script>abc.loader.load({apiToken:'', name:'',...});</script></body>`"

I have to change the object inside abc.loader.load() . 我必须更改abc.loader.load()的对象。 Is there any way I can pick up the object inside abc.loader.load() and make changes in javascript and replace with existing object. 有什么办法可以拾取abc.loader.load()的对象并在javascript中进行更改并替换为现有对象。

You can use a template literal and inject ${JSON.stringify(obj)} into that, like this: 您可以使用模板文字并将${JSON.stringify(obj)}注入其中,如下所示:

 <!-- var obj = {apiToken:'', name:''}; var html = `<!DOCTYPE html><html>....<body> <script>abc.loader.load(${JSON.stringify(obj)});</script></body></html>`; console.log(html); --> 

The script content is wrapped in <!-- --> to avoid misinterpretation of < inside your string. 脚本内容包装在<!-- -->以避免在字符串中误解<

Reading out the object and writing it again after mutation: 读出对象并在突变后再次将其写入:

Although I would try to stick to the above template string, and would repeat the injection of different objects into it, here is what you could do when you have a given HTML string, and need to extract the object. 尽管我会尝试坚持上面的模板字符串,并重复向其中注入不同的对象,但是当您拥有给定的HTML字符串并需要提取对象时,可以执行以下操作。 This only works if the object literal is JSON compliant, ie it double quotes strings, and also property names: 这仅在对象文字符合JSON的情况下才有效,即,它用双引号括住字符串以及属性名:

 <!-- var html = `<!DOCTYPE html><html>....<body> <script>abc.loader.load({"apiToken":"", "name":""});</script></body></html>`; html = html.replace(/(loader\\.load\\()(.*?)(?=\\);<\\/script>)/, function (_, prefix, json) { var obj = JSON.parse(json); // get the object obj.test = 3; // modify the object as you wish return prefix + JSON.stringify(obj); // put the object }); console.log(html); --> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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