From 8823f2a12ce1e567cdf57b66258d1a6d064e71fa Mon Sep 17 00:00:00 2001 From: Tiamenti Date: Sat, 1 Jun 2024 22:50:36 +0300 Subject: [PATCH] Implement FormattedString method --- src/format.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/format.ts b/src/format.ts index f8a5a68..f33e4ec 100644 --- a/src/format.ts +++ b/src/format.ts @@ -42,6 +42,42 @@ class FormattedString implements Stringable { this.entities = entities; } + /** + * Replaces matches of a pattern with a replacement string + * + * @param searchValue The pattern to search for + * @param replaceValue The string to replace the pattern with + * @returns A new `FormattedString` with replacements + */ + replace(searchValue: string | RegExp, replaceValue: string): FormattedString { + const newText = this.text.replace(searchValue, replaceValue); + + const newEntities = this.entities.map(entity => { + const newEntity = { ...entity }; + + if (typeof searchValue === 'string') { + const index = this.text.indexOf(searchValue); + + if (index !== -1 && index < newEntity.offset + newEntity.length) { + newEntity.offset = newEntity.offset + replaceValue.length - searchValue.length; + } + } else { + const match = this.text.match(searchValue); + + if (match) { + const index = match.index!; + if (index !== -1 && index < newEntity.offset + newEntity.length) { + newEntity.offset = newEntity.offset + replaceValue.length - match[0].length; + } + } + } + + return newEntity; + }); + + return new FormattedString(newText, newEntities); + } + /** * Returns the string representation of this object */