Handlebars JS 替换字符串的一部分

use*_*264 4 javascript node.js handlebars.js

我正在尝试创建一个名为“替换”的助手。我知道已经有一个了,但在我的一生中,我似乎无法弄清楚如何仅替换字符串的一部分并返回其余部分

<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"
}
Run Code Online (Sandbox Code Playgroud)

帮手

Handlebars.registerHelper('replace', function( find, replace, options) {
    var string = options.fn(this);
    return string.replace( find, replace );
});
Run Code Online (Sandbox Code Playgroud)

我似乎所能做的就是替换整个字符串,而不是字符串的一小部分。在本例中,将 & 符号替换为单词 and。

我确信这很容易,但除了用单词 and 替换整个块之外,我似乎无能为力。

任何建议都非常感激

wsc*_*rge 5

所指var string = options.fn(this);的是助手内部的内容,例如两个括号结构之间的内容:

{{#helperName}}this{{/helperName}}
Run Code Online (Sandbox Code Playgroud)

那么你的助手调用现在正在做什么是:

  1. 试图更换find = '&'里面this = 'and'
  2. 和你的title = 'The Amazing Red & Tshirt'

你应该做的是这样调用你的助手:

{{#replace "&amp;" "and"}}{{title}}{{/replace}}
Run Code Online (Sandbox Code Playgroud)

请注意作为参数传递的整个实体而不是单个&字符。