javascript - 使用对象更改文本中的单词 - javascript
问题描述
所以我需要使用对象 Eg 更改 textarea 中的所有单词
“我想通过考试,但我想我会失败”
“我想通过考试,但我想我会失败”
像这样的东西..(我需要用数组来制作)
<textarea id="text" placeholder="Enter text"></textarea>
<input type="button" value="Just Do It" id="submit">
const realText = document.querySelector('#text');
const submit = document.querySelector('#submit');
const words = {
'wanna':'want to',
'gonna':'going to',
}
submit.addEventListener('click', () => {
for(let key in words){
var arr = realText.value.split` `;
for(let i in arr){
if(arr[i] == key){
arr[i] = words[key];
}
else if(arr[i] == words[key]){
arr[i] = key;
}
}
}
});
解决方案
您可以使用正则表达式
<textarea id="text" placeholder="Enter text"></textarea>
<input type="button" value="Just Do It" id="submit">
const realText = document.querySelector('#text');
const submit = document.querySelector('#submit');
const words = {
'wanna':'want to',
'gonna':'going to',
}
submit.addEventListener('click', () => {
for (let key in words) {
var pattern = new RegExp(key, "g");
realText = realText.trim().replace(pattern,words[key])
}
submit = realText; // This will have replaced text
console.log(submit);
});
推荐阅读
- php - 在 PHP 表单的 onClick 事件中动态添加“ID”
- javascript - 新 - TypeError: undefined is not a Function
- javascript - 将鼠标悬停在导航栏的内容上会导致整个栏展开
- linux - 如何在正则表达式中找到的两个字符之间插入新行
- grammar - 寻找给定语言的语法?(Type-0 语法递归可枚举语言)
- flutter - Flutter 从 JSON 数据添加到收藏功能
- python - 为什么我的函数不显示 Pi 相机的结果?
- python - 问题围绕堆叠的子图以虚线堆叠在彼此之上
- java - 如何在重置整个代码的while语句中创建一个循环,或者如果用户输入“否”它允许退出
- arrays - 无法设置 PivotItem 类的 Visible 属性