The problem is that you always replace { with {} , even if the bracket is already matched. Instead, you should make sure that this is not a negative view : /\{(?!\})/
To fix the backspace problem, you should instead use an event that can tell you which key was pressed, like
onkeyup and add a security sentence. Expanding on the idea of @Andi, I also added an exception for the arrow keys so that you are not forced to the end of the text field when you want to move around the text:
var element = document.getElementById('textbox'); element.onkeyup = function(){ if([8, 37, 39].indexOf(event.which) != -1) return false; var code = (function(){ var val = element.value; element.value = val.replace(/\{(?!\})/g, "{}"); })(); };
source share