所以我需要使用对象E来更改文本区域中的所有单词
“我想通过考试,但我想我会失败的。”
“我想通过考试,但我想我会失败的。”
类似这样的..(我需要用数组制作)
<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;
}
}
}
});
尝试一下
const realText = document.querySelector('#text');
const submit = document.querySelector('#submit');
const words = {
'wanna':'want to',
'gonna':'going to',
}
submit.addEventListener('click', () => {
var arr = realText.value.split` `;
for(let i in arr){
if(words[arr[i]]){
arr[i] = words[arr[i]];
}
}
realText.value = arr.join(' ')
});
<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', () => {
// trim removes whitespaces
var arr = realText.value.trim().split(" ");
for (let key in words) {
for (let i in arr) {
if (arr[i] === key) {
arr[i] = words[key];
}
}
}
console.log(arr);
});
<textarea id="text" placeholder="Enter text"></textarea>
<input type="button" value="Just Do It" id="submit">
您可以使用正则表达式
<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);
});