Check pressed space then add diez tag using jquery with multi language

前端 未结 7 1487
感动是毒
感动是毒 2021-01-17 08:06

I am trying to add Diez tag # after the pressed space using jquery when user type. I have created this DEMO from codepen.io.

In this d

相关标签:
7条回答
  • 2021-01-17 09:03

    I made nearly perfect solution for you. Check it out on Codepen!

    Complete code:

    var input;
    
    function diez(event){
       var s = event.target.selectionStart;
       var e = event.target.selectionEnd;
       var v = event.target.value;
       var c = v.length;
           v = v.replace(/[^a-z0-9\s]/ig, ""); // line 8
       var a = v.split(" ");
       var b = [];
    
       /* Remove this if-block if you want undeletable diez */
       if(v == ""){
          event.target.value = v;
          return;
       }
       /* --- */
    
       for(var i = 0; i < a.length; i++){
          var token = a[i];
          if(i == 0) b.push("#" + token);
          else if(i > 0){
             var previous = a[i-1];
             if(previous.toLowerCase() != token.toLowerCase() && token != "")
                b.push("#" + token);
             else if (token == "")
                b.push(token);
          }
       }
    
       b = b.join(" ");
       c = b.length - c;
       event.target.value = b;
       event.target.selectionStart = s + c;
       event.target.selectionEnd = e + c;
    }
    
    $(document).ready(function() {
       input = document.getElementById("text");
       input.addEventListener("keyup", diez, true);
    });
    
    • Uses jQuery only for document ready event.
    • Keeps user selection and cursor position.
    • Vanilla Javascript code.
    • Replaced hacky content-editable div with a proper <input>.
    • Works on keypress, not on space press.

    UPDATE

    • You can no longer type special characters: anything, except letters a-z, 0-9 and whitespace. You can add whitelisted characters on line 8 (e.g russian, turkish)

    • Tokens that look alike are rejected.

    0 讨论(0)
提交回复
热议问题