繁体   English   中英

从某个字符javascript替换字符串

[英]replace string from a certain character javascript

我为我的应用程序创建了一个自定义@mention系统,我唯一的问题是开始输入@...不适,然后我选择了我要提及的用户,然后发生的事情是所选用户的名称刚刚添加到最后。的textarea这样就可以了。如果我只输入@但是如果我输入@ja ,然后选择jason smith ,现在会显示@jaJason 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
}

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

编辑

它已经引起我注意,这不是最好的方法,因为如果用户将光标移到中间并输入@,名称将被添加到字符串的末尾而不是@,所以我的问题是我在@之后替换了字符串,但是可以在textarea的任何地方使用它?

任何帮助,将不胜感激!

这是解决方案的简化版本。 我没有您的安装程序可以对此进行测试,当然可以采用一种更清洁的方法来进行此操作,但这应该使您对下一步的想法有所了解。

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;
}

我跳过了获取dom的部分, str表示textarea的值, placeholder表示当前的智能感知, username指的是真实的用户名,而position是可以通过document.getElementById('textarea').selectionStart确定的光标位置

 const str = 'adfsaf @ adsfsad @ja!2123afd @eeeav @asedf'; const position = 20; // just after @ja, str[20] gives the space ' ' after @ja const placeholder = '@ja'; // you should be able to get that dynamically. const username = 'Jason Smith'; // you should be able to get that dynamically. const idx = str.substring(0,position).indexOf(placeholder); const output = `${str.substring(0,position - placeholder.length)}@${username} ${str.substring(position)}`; console.log(output); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM