admin管理员组文章数量:1314832
I'm trying to create a helper called replace. I know there is one already, but for the life of me I can't seem to figure out how to replace just a portion of a string and return the rest
<div class="entry">
<h1>{{#replace "&" title}}and{{else}}{{/replace}}
</h1>
<div class="body">
{{body}}
</div>
</div>
{
title: "The Amazing Red & Tshirt",
body: "This is a short story about the red t-shirt"
}
Helper
Handlebars.registerHelper('replace', function( find, replace, options) {
var string = options.fn(this);
return string.replace( find, replace );
});
All I seem to be able to do is replace the entire string, rather than a small segment of the string. in this instance replacing the & symbol with the word and.
I'm sure it's easy, but I can't seem to do anything other than replacing the entire block with the word and.
Any suggestions greatly appreciated
I'm trying to create a helper called replace. I know there is one already, but for the life of me I can't seem to figure out how to replace just a portion of a string and return the rest
<div class="entry">
<h1>{{#replace "&" title}}and{{else}}{{/replace}}
</h1>
<div class="body">
{{body}}
</div>
</div>
{
title: "The Amazing Red & Tshirt",
body: "This is a short story about the red t-shirt"
}
Helper
Handlebars.registerHelper('replace', function( find, replace, options) {
var string = options.fn(this);
return string.replace( find, replace );
});
All I seem to be able to do is replace the entire string, rather than a small segment of the string. in this instance replacing the & symbol with the word and.
I'm sure it's easy, but I can't seem to do anything other than replacing the entire block with the word and.
Any suggestions greatly appreciated
Share Improve this question edited Jan 7, 2019 at 6:54 wscourge 11.3k17 gold badges63 silver badges86 bronze badges asked Feb 15, 2017 at 9:42 user125264user125264 1,8272 gold badges27 silver badges55 bronze badges1 Answer
Reset to default 5What is var string = options.fn(this);
reffering to is what's inside the helper, like between the two constructs of brackets:
{{#helperName}}this{{/helperName}}
So what is your helper call doing at the moment is:
- trying to replace
find = '&'
inside thethis = 'and'
- with your
title = 'The Amazing Red & Tshirt'
.
What you should do is calling your helper this way:
{{#replace "&" "and"}}{{title}}{{/replace}}
Do notice the whole entity passed as an argument instead of the single & character.
本文标签: javascriptHandlebars JS replacing portion of stringStack Overflow
版权声明:本文标题:javascript - Handlebars JS replacing portion of string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741972365a2407917.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论