I am trying to make a hashtag system using jquery but i have a question about the special character, ctrl+V
and mause right click paste
. I don't want to allow ctrl+v
and right click paste and also i don't want to allow special character like (*/-+()[]{}?-_^|!'"<>&%,.:
;`).
Can we do it in my code anyone can help me here please ?
Here is the DEMO page
In this demo you can see when you write for example how are you then the jquery code automatically adding diez(#
) symbol before the world like this #how #are #you
.
Here is the quick code:
$(document).ready(function() {
$("body").on("keyup", "#hash", function(event) {
var keyCode = event.keyCode;
// Allow: backspace, delete, tab, escape et enter
if (
$.inArray(keyCode, [46, 8, 27]) !== -1 ||
// Allow: Ctrl+A, Command+A
(keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) ||
// Allow: Ctrl+Z, Command+Z
(keyCode == 90 && (event.ctrlKey === true || event.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(keyCode >= 35 && keyCode <= 40)
) {
// let it happen, don't do anything
return;
}
if ($.inArray(keyCode, [32, 9, 13]) !== -1) {
var $textarea = $(this);
var text = $textarea.val();
text = XRegExp.replaceEach(text, [
[/#\s*/g, ""],
[/\s{2,}/g, " "],
[
XRegExp(
"(?:\\s|^)([\\p{L}\\p{N}]+)(?=\\s|$)(?=.*\\s\\1(?=\\s|$))",
"gi"
),
""
],
[XRegExp("([\\p{N}\\p{L}]+)", "g"), "#$1"]
]);
$textarea.val(text);
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
});
});
.hash {
position:relative;
width:100%;
border:1px solid #d8dbdf;
outline:none;
padding:15px;
color:#292929;
}
.hash:focus {
border:1px solid red;
}
.container {
position:relative;
width:100%;
max-width:600px;
margin:0px auto;
margin-top:100px;
}
<script src="https://unpkg.com/xregexp@3.2.0/xregexp-all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="hash" id="hash" placeholder="Write your word and press enter"/>
</div>