how to auto close brackets and braces in javascript?

Here’s an example using a Map to store characters and their matching closing characters which allows easy addition or customization of character pairs. Map.get() fetches the specified element from the map or returns undefined which allows for compact checking.

It’s also uses an input listener instead of keyup since you don’t need to detect modifier keys and feels a little more responsive (though not supported by IE < 9)

const closeChars = new Map([
  ['{', '}'],
  ['[', ']'],
  ['(', ')']
]);
    
maintextarea=document.getElementById('maintextarea');

maintextarea.addEventListener('input', function (e) {

    const pos = e.target.selectionStart;
    const val = [...e.target.value];
    
    const char = val.slice(pos-1, pos)[0];
    const closeChar = closeChars.get(char);
    
    if (closeChar) {
      val.splice(pos, 0, closeChar);
      e.target.value = val.join('');
      e.target.selectionEnd = pos;
    }
});
<textarea id="maintextarea" name="closebrackets" rows="8" cols="50">
</textarea>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top