diff --git a/src/placeholder.ts b/src/placeholder.ts index 2a7e082..3b0cba6 100644 --- a/src/placeholder.ts +++ b/src/placeholder.ts @@ -77,10 +77,12 @@ class Substitutor { } replace(): string { - const result: string[] = []; + const result: (string | StringSection)[] = []; let escaping = false; let hasSuffix = false; + let sectionOffset = -1; + let sectionLength = 0; while (this.#pos < this.#input.length) { const c = this.#input.charAt(this.#pos); @@ -90,7 +92,21 @@ class Substitutor { escaping = false; } else if (c === this.#substitutor.escapeChar) { escaping = true; + + if (sectionOffset >= 0) { + result.push(this.#input.subSection(sectionOffset, sectionLength)); + + sectionOffset = -1; + sectionLength = 0; + } } else if (this.tryAdvance(this.#substitutor.pattern.prefix)) { + if (sectionOffset >= 0) { + result.push(this.#input.subSection(sectionOffset, sectionLength)); + + sectionOffset = -1; + sectionLength = 0; + } + const innerSubstitutor = new Substitutor(this.#substitutor, this.#input.subSection(this.#pos), true); const variable = innerSubstitutor.replace(); @@ -111,22 +127,26 @@ class Substitutor { this.#pos += innerSubstitutor.#pos; continue; - } else if (this.tryAdvance(this.#substitutor.pattern.suffix)) { - if (this.#inner) { - hasSuffix = true; - break; + } else if (this.#inner && this.tryAdvance(this.#substitutor.pattern.suffix)) { + hasSuffix = true; + break; + } else { + if (sectionOffset < 0) { + sectionOffset = this.#pos; } - throw new PlaceholderException(this.#input.getSection(), this.#pos, "Missing prefix"); - } else { - result.push(c); + sectionLength++; } this.#pos++; } + if (sectionOffset >= 0) { + result.push(this.#input.subSection(sectionOffset, sectionLength)); + } + if (this.#inner && !hasSuffix) { - throw new PlaceholderException(this.#input.getSection(), this.#pos, "Missing suffix"); + throw new PlaceholderException(this.#input.getSection(), this.#pos, "Missing variable end delimiter"); } return result.join(""); diff --git a/src/string-section.ts b/src/string-section.ts index d19fade..abcacb6 100644 --- a/src/string-section.ts +++ b/src/string-section.ts @@ -44,4 +44,12 @@ export class StringSection { public substring(beginIndex: number = 0, endIndex: number = this.#length - beginIndex) { return this.#parent.substring(this.#offset + beginIndex, this.#offset + endIndex); } + + public toJSON() { + return this.getSection(); + } + + public toString() { + return this.getSection(); + } }