@opengis/fastify-table
Version:
core-plugins
61 lines (55 loc) • 1.78 kB
JavaScript
/**
* Виконує заміну символів у строці. Є можливість заміни регулярного виразу нової строки на тег <br>
*
* @summary Виконання заміни частини строки на значення з останнього аргументу.
* @priority 3
* @type helper
* @alias strReplace
* @tag string
* @example
* {{str_replace 'This Is Alias' ' ' ''}}
* @example
* {{{str_replace '<p>Перший рядок</p><p>Наступний рядок</p>' br=1}}}
* @example
* {{{str_replace 'Перший рядок<br>Наступний рядок' br=1}}}
* @param {Object} br
* @param {Object} newline
* @param {Object} html
* @param {Object} last
* @param {Array} args[0]]
* @param {Array} args[1]]
* @param {Array} args[2]]
* @returns {String} Returns HTML
*/
export default function strReplace(...args) {
const options = args.pop();
const [str, from, to] = args;
if (!str) return '';
if (options.hash.br) {
return str.replace(/\n/g, '<br>');
}
if (options.hash.newline) {
return str.replace(/\n/g, ' ');
}
if (options.hash.html) {
return str
.replace(/<br>/g, '\n')
.replace(/<\/p>/g, '\n')
.replace(/<\/li>/g, '\n')
.replace(/(<[^>]+>|<[^>]>|<\/[^>]>)/g, '')
.replace(/\n/g, ' ');
}
if (options.hash.last) {
return replaceLast(str, from, to);
}
if (typeof from !== 'string' || typeof to !== 'string') {
return 'Invalid replacement parameters';
}
return str.replace(new RegExp(from, 'g'), to);
}
function replaceLast(str, what, replacement) {
if (!str?.split) return str;
const pcs = str?.split(what);
const lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
}