Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars JS replacing portion of string

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

like image 377
user125264 Avatar asked Oct 15 '25 17:10

user125264


1 Answers

What 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:

  1. trying to replace find = '&' inside the this = 'and'
  2. with your title = 'The Amazing Red & Tshirt'.

What you should do is calling your helper this way:

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

Do notice the whole entity passed as an argument instead of the single & character.

like image 189
wscourge Avatar answered Oct 18 '25 07:10

wscourge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!