32 javascript string performance replace
嘿那里,我有一块HTML,我将重复使用(在用户访问期间的不同时间,而不是一次).我认为实现这一目标的最佳方法是创建一个HTML div,隐藏它,并在需要时使用其innerHTML并对几个关键字执行replace().作为示例HTML块...
<div id='sample'>
<h4>%TITLE%</h4>
<p>Text text %KEYWORD% text</p>
<p>%CONTENT%</p>
<img src="images/%ID%/1.jpg" />
</div>
Run Code Online (Sandbox Code Playgroud)
用动态数据替换这些关键字的最佳方法是...
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);
Run Code Online (Sandbox Code Playgroud)
感觉就像我选择了一种愚蠢的方式来做到这一点.有没有人对如何以任何方式更快,更智能或更好地做到这一点有任何建议?此代码将在用户访问期间经常执行,有时常常每3-4秒执行一次.
提前致谢.
som*_*ome 80
看起来你想要使用模板.
//Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output.
function template( templateid, data ){
return document.getElementById( templateid ).innerHTML
.replace(
/%(\w*)%/g, // or /{(\w*)}/g for "{this} instead of %this%"
function( m, key ){
return data.hasOwnProperty( key ) ? data[ key ] : "";
}
);
}
Run Code Online (Sandbox Code Playgroud)
代码说明:
templateid
成为现有元素的id.data
成为数据的对象.%keys%
(或者{keys}
如果您使用备用版本).键可以是AZ,az,0-9和下划线_的组合.模板示例:
<div id="mytemplate">
<p>%test%</p>
<p>%word%</p>
</div>
Run Code Online (Sandbox Code Playgroud)
通话示例:
document.getElementById("my").innerHTML=template("mytemplate",{test:"MYTEST",word:"MYWORD"});
Run Code Online (Sandbox Code Playgroud)
Kri*_*nck 18
您可以调整此代码以执行您想要的操作:
var user = {
"firstName": "John",
"login": "john_doe",
"password": "test",
};
var textbody = ""
+"Hey {firstName},\n"
+"\n"
+"You recently requested your password.\n"
+"login: {login}\n"
+"password: {password}\n"
+"\n"
+"If you did not request your password, please disregard this message.\n"
+"";
textbody = textbody.replace(/{[^{}]+}/g, function(key){
return user[key.replace(/[{}]+/g, "")] || "";
});
Run Code Online (Sandbox Code Playgroud)
您可能还想查看JavaScriptTemplates
Vil*_*lx- 12
我怀疑会有更高效的东西.替代方案是将其拆分为多个部分,然后连接,但我认为这不会有效.或许甚至更少,考虑到每个连接都会产生一个与其操作数大小相同的新字符串.
补充:这可能是最优雅的写作方式.此外 - 你还担心什么?内存使用情况?它很丰富,Javascript有一个像样的内存管理器.执行速度?然后你必须有一些巨大的字符串.恕我直言这很好.
Lio*_*rom 10
一个快速简便的解决方案是使用String.prototype.replace方法.它需要第二个参数,可以是值或函数:
function replaceMe(template, data) {
const pattern = /{\s*(\w+?)\s*}/g; // {property}
return template.replace(pattern, (_, token) => data[token] || '');
}
Run Code Online (Sandbox Code Playgroud)
const html = `
<div>
<h4>{title}</h4>
<p>My name is {name}</p>
<img src="{url}" />
</div>
`;
const data = {
title: 'My Profile',
name: 'John Smith',
url: 'http://images/john.jpeg'
};
Run Code Online (Sandbox Code Playgroud)
并称之为:
replaceMe(html, data);
Run Code Online (Sandbox Code Playgroud)