簡體   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