Javascript 将车把转换为小写和破折号
我试图在前端重用模板中的一些数据 为此,我需要将其中一个表达式转换为小写,并使用破折号而不是空格。这容易做到吗 例如,在我的JSON文件中,我有以下内容:Javascript 将车把转换为小写和破折号,javascript,regex,ember.js,handlebars.js,Javascript,Regex,Ember.js,Handlebars.js,我试图在前端重用模板中的一些数据 为此,我需要将其中一个表达式转换为小写,并使用破折号而不是空格。这容易做到吗 例如,在我的JSON文件中,我有以下内容: var items = [{ id: '1', title: "Item Number One", }, { id: '2', title: "Item Number Two", }, ]; 在前端的扶手模板上,我想这样做: <script type="text/x-handlebars" id="
var items = [{
id: '1',
title: "Item Number One",
},
{
id: '2',
title: "Item Number Two",
},
];
在前端的扶手模板上,我想这样做:
<script type="text/x-handlebars" id="items">
<h1>
{{title}}
</h1>
<img src="{{unbound title}}.png" />
</script>
{{title}}
这会将图像页面输出为
,这不好。那么,有没有一种简单的方法将其转换为小写,并删除空格 您可以映射items数组并将模板应用于修改后的数组,如下所示:
var items = [
{
id: '1',
title: "Item Number One",
},
{
id: '2',
title: "Item Number Two",
},
];
items = items.map(function(el) {
el.title = el.title.toLowerCase().replace(/\s+/g, '-');
return el;
});
// items = [{id:"1",title:"item-number-one"},{id:"2",title:"item-number-two"}]
如果需要保留原始数组,只需将映射的数组指定给其他变量。制作一个自定义把手辅助对象:
Handlebars.registerHelper("noSpaces", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
然后称之为:
<img src="{{noSpaces title}}.png" />
它是如何从
{{unbound title}}
发展到第一项的
?它正在使用。