How to develop an Auto Text Expander with JavaScript or jQuery?

2

I want to create multiple keywords to work as a shortcut to auto completion.

"oi." daria "Olá Amigo"

"ate." daria "Abraço e até mais"

For example, I type in a textarea of my site the word "test." and automatically and immediately this shortcut turns the phrase "complete my test sentence" and as I type more shortcuts that match, everything will be completed.

It has a Chrome extension that does this, however I want to develop with JS to do this functionality inside my site. This way you can write a giant text in a textarea to send as a message, saving time.

Click here and see the extension I'm talking about.

    
asked by anonymous 05.06.2017 / 08:56

1 answer

2

This is simple, you have to have an object with the short and long versions of each sentence and then use something like this:

var atalhos = {
  'oi.': 'Olá Amigo',
  'ate.': 'Abraço e até mais'
}

var textarea = document.querySelector('textarea');
textarea.addEventListener('keyup', function(e) {
  for (var chave in atalhos) {
    // substituir caso haja algum match
    var _chave = chave.replace(/[-[\]{}()*+?.,\^$|#\s]/g, '\$&');
    var regex = new RegExp('(^)' + _chave + '|(\s)' + _chave);
    var match = textarea.value.match(regex);
    if (!match) continue;
    match = match.filter(function(m){return typeof m !== 'undefined';});
    textarea.value = textarea.value.replace(regex, match[1] + atalhos[chave]);
  }
});
<textarea></textarea>
    
05.06.2017 / 09:05