Storing the line number of all the occurrence of particular character in javascript

你离开我真会死。 提交于 2019-12-04 02:13:28

问题


I am following this link Find out the 'line' (row) number of the cursor in a textarea. I want to store the line number of all the occurence of "{" in array while user write in textarea. I want to display the array content after it.

Here is source code , I have tried:

<textarea rows="10" cols="100" id="editor" onkeypress="hello(event);" ></textarea>
<div id="lineNo"></div>

<script>

    function hello(e)
    {
        var keyp=e.charCode;
        var c=0,i;
        var arr=new Array();
        if(keyp=='123')
        {
            var arr[c++]=getLineNumber();               
        }
        for (i=0;i<arr.length;i++)
        {
            document.getElementById("lineNo").innerHTML="Array content is...   "+ arr[i];
            //document.write(arr[i] + "<br >");
        }       
    }
    function getLineNumber() {
        var textarea=document.getElementById("editor")
        var x=textarea.value.substr(0, textarea.selectionStart).split("\n").length;
        return x;
    }

</script>

But array content is not displaying. Please suggest me what is wrong in code and also if possible please tell me a better way to store the line number of all the occurence of particular character in javascript and display it.


回答1:


Is this something you want to do:

<textarea rows="10" cols="100" id="editor" onkeypress="hello(event);" ></textarea>
<div id="lineNo"></div>
<script>
  var arr = [];
  var c = 0;
  function hello(e) {
    var keyp=e.charCode; 
    if(keyp=='123') {
      arr[c++] = getLineNumber();
    }

    document.getElementById("lineNo").innerHTML=
      "Array content is...   "+ arr.join(' ');      
  }
  
  function getLineNumber() {
    var ta=document.getElementById("editor")
    var x=ta.value.substr(0, ta.selectionStart).split("\n").length;
    console.log(x)
    return x;
  }
</script>


来源:https://stackoverflow.com/questions/54178687/storing-the-line-number-of-all-the-occurrence-of-particular-character-in-javascr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!