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

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

问题描述

嘿,我有一个 HTML 块,我将要重复使用它(在用户访问期间的不同时间,而不是一次).我认为完成此操作的最佳方法是创建一个 HTML div,将其隐藏,并在需要时获取其 innerHTML 并对多个关键字执行 replace().作为示例 HTML 块...

<h4>%TITLE%</h4><p>文字文字 %KEYWORD% 文字</p><p>%CONTENT%</p><img src="图片/%ID%/1.jpg"/>

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

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 秒执行一次.

提前致谢.

解决方案

我怀疑会有什么更有效的方法.另一种方法是将其分成几部分然后连接,但我认为这不会很有效率.考虑到每次连接都会产生一个与其操作数具有相同大小的新字符串,可能甚至更少.

补充:这可能是最优雅的写法.另外——你担心什么?内存使用情况?它很丰富,而且 Javascript 有一个不错的内存管理器.执行速度?那么你一定有一些巨大的字符串.恕我直言,这很好.

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);

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.

Thanks in advance.

解决方案

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.

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天全站免登陆