简体   繁体   中英

Implementing snippets in a textarea

I'm trying to implement snippets into an html textarea. You write a certain word and it will look through key value object and expand the text if it exists. Here is what I have done:

var textarea = document.getElementById("whatever");
var snippets = {
    'hello': 'Hello and welcome to my great site'
}
var prepend = "";

var checkCaps = function(e){
  if (e.keyCode != 9) return;
  e.preventDefault();
  var string = "";
  var pos = textarea.selectionStart;
  var text = textarea.value.split("");
  while (pos) {
    char = text.pop(pos);
    prepend =  (char == " ") ? " ": ""; 
    if (char == " ") break;
    string += char 
    pos -= 1;
  }
  if (snippets[string.reverse()]) {
      textarea.value = text.join("")
      textarea.value += prepend + snippets[string.reverse()]
  }
}


textarea.addEventListener("keydown", checkCaps, false);

String.prototype.reverse=function(){return this.split("").reverse().join("");}

http://jsfiddle.net/JjTmd/

The problem is that the snippet only works in the last word of the textarea's value , and I can't seem to pinpoint where the problem is.

Array.pop doesn't accept a parameter. It removes and returns the last item from the array. Use splice to remove an item at a particular index.

I modified your function as follows and it seems to have the desired behavior:

var checkCaps = function(e){
  if (e.keyCode != 9) return;
  e.preventDefault();
  var string = "";
  var pos = textarea.selectionStart;
  var text = textarea.value.split("");
  while (pos) {
    char = text.splice(pos-1,1);
    prepend =  (char == " ") ? " ": ""; 
    if (char == " ") break;
    string += char 
    pos -= 1;
  }
  if (snippets[string.reverse()]) {
      var start = text.splice(0, pos);
      var end = text.splice(pos + string.length);

      textarea.value = start.join("") + snippets[string.reverse()] + prepend + text.join("") + end.join("");
  }
}

http://jsfiddle.net/JjTmd/1/

Also, you'll probably want to check for new line characters as well:

while (pos) {
    char = text.splice(pos-1,1);

      if (char == " " || char == "\n") {
          prepend = char;
          break;
      }
    string += char 
    pos -= 1;
}

http://jsfiddle.net/JjTmd/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM