You have three situations:
- The user presses
backspace
and deletes the char before the cursor
- The user presses
canc
and deletes the char after the cursor
- The user selects the text and presses
backspace
or canc
and deletes the selected text
So you have to work around all these different situations.
This code will work:
$('#textareaId')[0].addEventListener("keydown", function(e) {
var start = this.selectionStart,
end = this.selectionEnd,
value = this.value,
key = e.keyCode;
if (key == 8 && value[start-1] == '/') e.preventDefault();
if (key == 46 && value[start] == '/') e.preventDefault();
if ((key == 8 || key == 46) && value.substring(start, end).indexOf('/') != -1) e.preventDefault();
}, false);
WORKING EXAMPLE: http://jsfiddle.net/MeBeiM/7hdb3472/1