Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i replace a { with {}

I am trying to develop a braces auto completion feature in a text box. I tried the javascript replace function on the textbox. But i am getting a weird output from the function. Here's the code i am work on.

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<input type ="text" id="textbox">
</body>
</html>

Javascript:

var element = document.getElementById('textbox');
element.oninput = function(){
 var code = (function(){
      var val = element.value;
      element.value = val.replace(/\{/ , "{}");  
 })();
};

When i type a single { brace i am getting {} , when i type more than 1 i am getting {}}}{{ and it goes on .. sometimes my browser freezes when i try to clear the braces.

Here's the js bin link JSBIN

like image 625
Xcoder Avatar asked Mar 16 '23 03:03

Xcoder


1 Answers

The problem is that you are always replacing { with {}, even if the bracket has already been matched. You should instead ensure it was not with negative lookahead: /\{(?!\})/


To fix the backspace issue, you should instead be using an event which can tell you which key was pressed like onkeyup and add a guard clause. Expanding on @Andi's idea, I also added exclusion for the arrow keys so you won't be forced to the end of the textbox when you want to navigate through 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, "{}");  
    })();
};
like image 198
ndnenkov Avatar answered Mar 29 '23 10:03

ndnenkov