Изменение слов в тексте с помощью объекта - javascript - PullRequest
0 голосов
/ 22 марта 2020

Так что мне нужно изменить все слова в текстовой области, используя объект Eg

"I want to pass the exams, but I think I'm gonna fail"
"I wanna pass the exams, but I think I'm going to fail"

Как-то так .. (мне нужно сделать это с массивами)

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

Ответы [ 3 ]

1 голос
/ 22 марта 2020

Попробуйте:

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">
1 голос
/ 22 марта 2020

Вы можете использовать регулярное выражение

<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);
});
0 голосов
/ 22 марта 2020

Попробуйте это

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">
...