javascript - 如何在 contenteditable div 中抓取某些单词
问题描述
编辑:textarea - > contenteditable div
我正在尝试制作一个脚本工具,它从 contenteditable div 中获取某个单词,然后将其更改为另一个单词。
为了更清楚地向您展示我的目标,该工具应该“看起来像”下面的代码段(尽管脚本尚未准备好):通过单击按钮,this is a sample text, this is another text
应将其替换为that is a sample text, that is another text
. 所有两个this
s 都切换到that
s。
<div contenteditable="true">this is a sample text, this is another text</div><br>
<button>change 'this' to 'that'</button>
所以我遇到了我的第一个问题;什么是在内容可编辑的 div 中抓取整个文本中的所有“特定单词”的方法?Jquery 解决方案也可能会有所帮助。
解决方案
我在这里为您的按钮和文本区域添加了一个 ID。
为此,您可以向按钮元素添加一个事件侦听器并让它侦听单击事件。
当按钮被按下时,使用 textContent 属性获取 div 的文本并使用 textContent 属性重新评估它,但使用replaceAll()方法将所有出现的旧词替换为新词。
document.getElementById('btn').addEventListener('click', replacer);
function replacer(){
let tx = document.getElementById('txarea');
tx.textContent = tx.textContent.replaceAll('this', 'that');
}
<div id="txarea">this is a sample text, this is another text</div><br>
<button id="btn">change 'this' to 'that'</button>
推荐阅读
- javascript - 如何将语言状态从 App.js 传递给 i18n.js 中的 i18n 函数?(I18n 反应)
- php - 看看字符串“真的”包含什么?
- reactjs - 在 reactjs 酶测试中,围绕测试渲染器和模拟事件包装 act 方法的正确方法是什么
- python - 从 pyplot 中突出显示和删除行
- amazon-web-services - 尝试通过 Terraform 检索 rds 端点并将其存储在 AWS 机密管理器中时出现“不允许变量”错误
- logging - JBoss server.log 在流中解析
- bash - 仅替换/删除在字符串中找到的第一个匹配项
- javascript - 我正在尝试使用 json 制作多语言网站“en & ar”,但 AR 内容出现 ltr,我怎样才能让 AR 出现 rtl 并且 EN 仍然是 ltr?
- javascript - 为什么 Intellisense 建议将 this["__#12345@#methodName"] 用于“私有”JS 方法?
- html - 如何在下拉选择标签VUEJS中显示来自api的选定值