JavaScript - What is the better way to skip an input when necessary for a code editor? -


i programming web app online code editor. 1 of basic functions when users input, say, left parenthesis symbol "(", editor automatically add right 1 ")" you.

so immediate idea create object that, defined follows:

var pairchardata = {     "{": "}",     "(": ")",     "\"":"\"",     "'":"'" }; 

that's not end. want editor smarter should skip input when necessary. example, when input in editor right parenthesis symbol after added left 1 (at time, right parenthesis existed!), editor expected move cursor without showing 1 more duplicated one.

so want check if next user-input character 1 expected.
created map follows:

var pairchardatareverse = {     "}": "{",     ")": "(",     "\"":"\"",     "'":"'" }; 

this is, know, reverse version of first map. idea keep track of input key users. here implementation

if(key in pairchardatareverse) { var leftpair = pairchardatareverse[key]; if(this.lastkey === leftpair) {     this.selectionstart = this.selectionend = start +1;     e.preventdefault(); } 

as add more pairs of characters, have modify both maps, not want.
guess there must better way store data less pain. maybe data structure or there trick wonder.

you can use <select> element <option> elements corresponding characters user selects wrap text within. user selects text, user selects <option>, javascript performs action wraps selected text in selected <option> .value.

var textarea = document.queryselector("textarea");  var select = document.queryselector("select");  var text;  select.onchange = function(e) {    if (text) {      var option = this.value.split("");      textarea.value = textarea.value.slice(0, text[0])                        + option[0]                        + textarea.value.slice(text[0], text[1])                       + option[1]                       + textarea.value.slice(text[1]);    }    this.value = text = null;  }  textarea.onselect = function(e) {    text = [this.selectionstart, this.selectionend]  }
<select>    <option></option>    <option value="()">()</option>    <option value="[]">[]</option>    </select><br>  <textarea></textarea>


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -