UNPKG

844 BJavaScriptView Raw
1'use strict';
2const common = require('../lib/common.js');
3
4function helper(paper) {
5 paper.handlebars.registerHelper('replace', function (needle, haystack) {
6 needle = common.unwrapIfSafeString(needle);
7 haystack = common.unwrapIfSafeString(haystack);
8
9 const options = arguments[arguments.length - 1];
10
11 if (typeof needle !== 'string') {
12 return options.inverse(this);
13 }
14
15 const regex = new RegExp(escapeRegex(needle), 'g');
16
17 // Yield block if true
18 if (typeof haystack === 'string' && regex.test(haystack)) {
19 return haystack.replace(regex, options.fn(this));
20 } else {
21 return options.inverse(this);
22 }
23 });
24}
25
26
27function escapeRegex(string) {
28 return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
29}
30
31module.exports = helper;