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

Asked

Viewed 155 times

2

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

"oi." daria "Olá Amigo"

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

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

There is an extension of Chrome that does this, but I want to develop with JS to make this functionality within 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 extent I’m talking about.

1 answer

2


That’s 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.