且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

高效的 Javascript 字符串替换

更新时间:2023-09-03 18:46:58

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

补充:这可能是最优雅的写法.另外——你担心什么?内存使用情况?它很丰富,而且 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.