Skip to content

Commit 4250e56

Browse files
author
Tom Hutman
committed
fix text replace algorithm so it doesn't randomly delete text at the beginning of the message
1 parent 80e3216 commit 4250e56

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/components/AutoCompleteTextarea/Textarea.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,12 +203,20 @@ class ReactTextareaAutocomplete extends React.Component {
203203

204204
const textToModify = textareaValue.slice(0, selectionEnd);
205205

206-
const startOfTokenPosition = textToModify.search(
207-
/**
208-
* It's important to escape the currentTrigger char for chars like [, (,...
209-
*/
210-
new RegExp(`\\${currentTrigger}${`[^\\${currentTrigger}${'\\s'}]`}*$`),
206+
// It's important to escape the currentTrigger char for chars like [, (,...
207+
const findTriggerRegExp = new RegExp(
208+
`\\${currentTrigger}${`[^\\${currentTrigger}${'\\s'}]`}*`,
211209
);
210+
// reverse the string so we can easily find the first index of the currentTrigger
211+
const reversedString = textToModify.split('').reverse().join('');
212+
// find the first instance of currentTrigger (-1 if not found)
213+
const distanceFromEndOfString =
214+
reversedString.search(findTriggerRegExp) + 1;
215+
// if found, distract from the length of the string to revert the position back to an actual string index.
216+
const startOfTokenPosition =
217+
distanceFromEndOfString === -1
218+
? 0
219+
: textToModify.length - distanceFromEndOfString;
212220

213221
// we add space after emoji is selected if a caret position is next
214222
const newTokenString =

0 commit comments

Comments
 (0)