首页 > 解决方案 > 使用对象更改文本中的单词 - 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;
            }
        }
    }
});

标签: javascriptarraysobjectjavascript-objectsword

解决方案


您可以使用正则表达式

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

推荐阅读