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
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);
});
<input>
.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.