0

I was following the link Storing the line number of all the occurrence of particular character in javascript which store the line number of all the occurence of "{" in array but only when the user type in textarea i.e on keypress. It was not working if we directly paste the content in textarea. So I used the onchange and match keyword to find and store the line number in array.

The textarea content is:

Hello {    
The next match here line number  {   
Bla Bla 
blah bla 
blah blah 
The next match here line number  {    
end textarea 

The desired output is: 1 2 6

But the output is showing the last number: 7

Please suggest me what is wrong in this code by giving the correct solution. I don't want to use jquery.

var arr = [];
var c = 0;

function hello() {
  var str = document.getElementById('editor').value;
  if (str.match(/{/)) {
    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;
  return x;
}
<textarea rows="30" cols="100" id="editor" onchange="hello();"></textarea>
<div id="lineNo"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ratnesh
  • 1,554
  • 3
  • 12
  • 28
  • Use the `input` event handler which also handles paste: `document.getElementById("editor").addEventListener("input",hello);` – mplungjan Jan 16 '19 at 09:10

1 Answers1

1

You can do this by splitting by newline and find the occurrence of { in each line.

  var arr = [];
  var c = 0;
  function hello() {
    var str=document.getElementById('editor').value; 
    lines = str.split(/\r?\n/);
    lines.forEach((line,index) => {      
        if (line.match(/{/)) {
          arr[c++] = index;  
        }
    })
    document.getElementById("lineNo").innerHTML=
      "Array content is...   "+ arr.join(' ');    
  }
<textarea rows="30" cols="100" id="editor" oninput="hello();" ></textarea>
<div id="lineNo"></div>
Vineesh
  • 3,762
  • 20
  • 37