gpt4 book ai didi

javascript - 替换字符串中的某个字符javascript

转载 作者:行者123 更新时间:2023-12-01 01:52:07 25 4
gpt4 key购买 nike

我已经为我的应用程序创建了一个自定义@mention系统,我唯一的问题是开始输入@...,然后我将选择我想要提及的用户,发生的事情是名称所选用户的名称只是添加到 textarea 的末尾,因此如果我只输入 @ 但如果我输入 @ja ,则此方法有效然后选择 jason smith 现在会显示 @jason Smith 如何删除 @ 之后输入的任何文本,然后添加到我的字符串中。仅供引用,这是在 textarea

中完成的

所以我当前的函数看起来像这样..

addMention(user: any): void {
const textarea = document.querySelector('textarea');
const mentionSelect = <HTMLElement>document.querySelector('.mention-container');
const value = textarea.value; // Store the value
textarea.value = `${textarea.value}${user.value}`; // Current Value
mentionSelect.style.display = 'none'; // Hide the mention list
this.message = textarea.value; // Make sure the new textarea value is stored in message
textarea.focus(); // refocus
textarea.value = ''; // clear
textarea.value = value; // add the value back in
}

所以发生的事情是我只是通过添加用户名来更新文本区域的值

编辑

这引起了我的注意,这不是最好的方法,因为如果用户将光标移动到中间并键入@,名称将被添加到字符串的末尾而不是@,所以我的问题我怎样才能替换@后面的字符串,但能够在文本区域的任何地方进行替换??

如有任何帮助,我们将不胜感激!

最佳答案

这是解决方案的简化版本。我没有你的设置来测试这个,当然有一个更干净的方法来做到这一点,但这应该让你知道该去哪里。

addMention(user: { value: string }): void {
const textArea = document.querySelector('textarea');
const selection = textArea.selectionStart;
let value = textarea.value;
const str = value.substring(0, textArea.selectionStart);
const index = str.lastIndexOf('@');
const mention = str.substring(index);
value = `${value.substring(0, index)}${user.value}${value.substring(index + mention.length)}`;
textarea.value = value;
}

关于javascript - 替换字符串中的某个字符javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com