Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement FormattedString method #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PQ!

Please consider this counterexample test case in your next commit.

bot.command('start', async ctx => {
  const msg = fmt`I like the grammY ${code('framework')} very much`;

  const newMsg = msg.replace('framework', 'library');

  await ctx.replyFmt(newMsg);
});

Result:
Screenshot 2024-06-02 at 10 45 35 AM

}
} 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
*/
Expand Down