refactor: core.utils.replaceText

This commit is contained in:
unanmed 2024-11-07 21:17:53 +08:00
parent 1f09332cb5
commit eccb29a524

View File

@ -33,24 +33,43 @@ utils.prototype._init = function () {
////// 将文字中的${和}(表达式)进行替换 ////// ////// 将文字中的${和}(表达式)进行替换 //////
utils.prototype.replaceText = function (text, prefix) { utils.prototype.replaceText = function (text, prefix) {
if (typeof text != 'string') return text; if (typeof text !== 'string') return text;
var index = text.indexOf('${'); let pointer = -1;
if (index < 0) return text; let res = '';
var cnt = 0, let expression = '';
curr = index; let blockDepth = 0;
while (++curr < text.length) { let inExpression = false;
if (text.charAt(curr) == '{') cnt++;
if (text.charAt(curr) == '}') cnt--; while (++pointer < text.length) {
if (cnt == 0) break; const char = text[pointer];
if (inExpression) {
if (char === '}') {
blockDepth--;
} else if (char === '{') {
blockDepth++;
}
if (blockDepth === 0) {
inExpression = false;
res += String(core.utils.calValue(expression, prefix));
expression = '';
} else {
expression += char;
}
continue;
}
if (char === '$' && text[pointer + 1] === '{') {
pointer++;
inExpression = true;
blockDepth++;
continue;
}
res += char;
} }
if (cnt != 0) return text;
var value = core.calValue(text.substring(index + 2, curr), prefix); return res;
if (value == null) value = '';
return (
text.substring(0, index) +
value +
core.replaceText(text.substring(curr + 1), prefix)
);
}; };
utils.prototype.replaceValue = function (value) { utils.prototype.replaceValue = function (value) {