UNPKG

ice.fo.utils

Version:

38 lines (31 loc) 1.2 kB
/* eslint-disable vue/max-len */ import _get from 'lodash/get'; import replaceAll from './replaceAll'; import getStringBetweenCharacters from './getStringBetweenCharacters'; /** * Ex: formatString({ username: "Nikochin" }, "{username} comes to rescue") => "Nikochin comes to rescue" * @param {*} target Object contains values * @param {*} pattern String input */ export default function formatStringValue(target, pattern, funcs = {}, prefix = '{', suffix = '}') { // const regExp = /{([^}]*)}/g // "get content {test}" => "{test}"" // const regExp = /[^{}]+(?=})/g // "get between content {test}" => "test" // const matches = pattern.match(regExp) const matches = getStringBetweenCharacters(pattern, prefix, suffix); if (!matches) { return pattern; } let result = pattern; matches.forEach((match) => { const find = prefix + match + suffix; const parts = match.replace(/\s/g, '').split(/\|/); let value = _get(target, parts[0]); if (parts.length > 1) { for (let i = 1; i < parts.length; i++) { value = funcs[parts[i]] ? funcs[parts[i]](value) : value; } } result = replaceAll(result, find, value); }); return result; }