gpt4 book ai didi

javascript - Handlebars JS 替换字符串的一部分

转载 作者:搜寻专家 更新时间:2023-11-01 00:38:45 24 4
gpt4 key购买 nike

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

<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"
}

助手

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

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

我敢肯定这很容易,但除了用单词 and 替换整个 block 之外,我似乎无能为力。

非常感谢任何建议

最佳答案

什么是 var string = options.fn(this); 指的是 helper 内部的内容,比如两个括号结构之间:

{{#helperName}}this{{/helperName}}

那么你的助手调用目前正在做什么:

  1. 尝试替换 this = 'and' 中的 find = '&'
  2. 您的 title = 'The Amazing Red & Tshirt'

你应该做的是以这种方式调用你的助手:

{{#replace "&amp;" "and"}}{{title}}{{/replace}}

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

关于javascript - Handlebars JS 替换字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com