1

I'm using this script to automatically place a comma space after each item you type and press the spacebar.

But for some reason I can not figure out how to make it backspace at all.

I would prefer it to be able to delete a whole item and trailing comma with each backspace.

   $('#textarea').keyup(function(){
   var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
   if (str!=this.value) this.value = str; 
   });

<textarea id='textarea'>item1, item2, item3</textarea>
4

1 回答 1

1

它只是启用退格:

$('#textarea').keyup(function(e) {
  if (e.which === 8) { // backspace detected
      return;
  }
  var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
  if (str!=this.value) this.value = str; 
});

编辑:完整版:

$('#textarea').keyup(function(e){
    var str = this.value;
    if (e.which === 8) {
        var tmp = str.split(', ');
        tmp.splice(tmp.length - 1, 1);
        str = tmp.join(', ');
        this.value = str;
        return;
    }
    str = str.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
    if (str!=this.value) this.value = str; 
});
于 2018-12-09T23:08:29.163 回答