高效的Javascript字符串替换 [英] Efficient Javascript String Replacement

查看:69
本文介绍了高效的Javascript字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿那里,我有一块HTML,我将重复使用(在用户访问期间的不同时间,而不是一次)。我认为实现这一目标的最佳方法是创建一个HTML div,隐藏它,并在需要时使用其innerHTML并对几个关键字执行replace()。作为示例HTML块......

Hey there, I've got a block of HTML that I'm going to be using repeatedly (at various times during a users visit, not at once). I think that the best way to accomplish this is to create an HTML div, hide it, and when needed take its innerHTML and do a replace() on several keywords. As an example HTML block...

<div id='sample'>
  <h4>%TITLE%</h4>
  <p>Text text %KEYWORD% text</p>
  <p>%CONTENT%</p>
  <img src="images/%ID%/1.jpg" />
</div>

用动态数据替换这些关键字的最佳方法是... ...

Would the best way to replace those keywords with dynamic data be to go...

template = document.getElementById('sample');
template = template.replace(/%TITLE%/, some_var_with_title);
template = template.replace(/%KEYWORD%/, some_var_with_keyword);
template = template.replace(/%CONTENT%/, some_var_with_content);
template = template.replace(/%ID%/, some_var_with_id);

感觉就像我选择了一种愚蠢的方式来做这件事。有没有人对如何以任何方式更快,更智能或更好地做到这一点有任何建议?此代码将在用户访问期间经常执行,有时常常每3-4秒执行一次。

It just feels like I've chosen a stupid way to do this. Does anyone have any suggestions on how to do this faster, smarter, or better in any way? This code will be executed fairly often during a users visit, sometimes as often as once every 3-4 seconds.

提前致谢。

推荐答案

我怀疑会有更高效的东西。替代方案是将其拆分为多个部分,然后连接,但我认为这不会有效。考虑到每个连接都会产生一个与其操作数大小相同的新字符串,可能更少。

I doubt there will be anything more efficient. The alternative would be splitting it into parts and then concatenating, but I don't think that would be much efficient. Perhaps even less, considering that every concatenation results in a new string which has the same size as its operands.

已添加:这可能是最优雅的写作方式。此外 - 你还担心什么?内存使用情况?它很丰富,Javascript有一个像样的内存管理器。执行速度?然后你必须有一些巨大的字符串。恕我直言,这很好。

Added: This is probably the most elegant way to write this. Besides - what are you worried about? Memory usage? It's abundant and Javascript has a decent memory manager. Execution speed? Then you must have some gigantic string. IMHO this is good.

这篇关于高效的Javascript字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆