@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
76 lines (75 loc) • 2.81 kB
JavaScript
// NOTE: BingChat came up with this regex:
/**
* const regex = /{{(.*?)}}/g;
*
* function replaceHandlebars(template, data) {
// Create a regular expression to match handlebars expressions
const regex = /{{(.*?)}}/g;
// Replace each expression with the corresponding value from the data object
return template.replace(regex, (match, expression) => {
// Evaluate the expression using the data object as the context
return eval(expression);
});
}
*/
import { HandleBarsRegex } from "./HandleBarsRegex";
/**
* This function will replace
* <h2>{{Title}}</h2>
*
* with the Title property of the item passed in:
* <h2>item.Title</h2>
*
* @param item
* @param handleBarString
* @param emptyIfSubEmpty
* @param replaceSlashDots >> will replace Author/Title with AuthorTitle - consistant with the way Drilldown works
* @returns
*/
export function replaceHTMLHandleBars(item, handleBarString, emptyIfSubEmpty, replaceSlashDots = true) {
if (typeof handleBarString !== 'string') {
return handleBarString;
}
else {
let returnEmpty = false;
// Get array of strings by splitting the string by any {{ or }}
const linkSplits = handleBarString.split(HandleBarsRegex);
const newSplits = linkSplits.map((str, idx) => {
if (idx % 2 === 1) { //idx is odd. This is a replacement
// https://github.com/mikezimm/drilldown7/issues/396
if (replaceSlashDots === true)
str = str.replace(/[./]/g, '');
str = item[str] ? item[str] : `No ${str} found`;
if (!linkSplits[idx] && emptyIfSubEmpty === true)
returnEmpty = true;
}
return str;
});
return returnEmpty === true ? '' : newSplits.join('');
}
}
/**
* This will get all properties that are surrounded by handlebars from a string and put them in an array
* Recommended to get item props to fetch or select
* Does NOT remove any / or . characters.
*
* @param handleBarString
* @param removeEmpty
* @param removeDups
* @returns
*/
export function getHandleBarPropsFromString(handleBarString, removeEmpty, removeDups) {
const results = [];
const linkSplits = handleBarString.split(HandleBarsRegex);
linkSplits.map((str, idx) => {
if (idx % 2 === 1) { //idx is odd. This is a replacement
if (str || removeEmpty === false) {
if (removeDups === false || results.indexOf(`${str}`) === -1)
results.push(`${str}`);
}
}
});
console.log('getHandleBarPropsFromString', results, handleBarString);
return results;
}
//# sourceMappingURL=handleBarsHTML.js.map