Search code examples
javascriptstringcharactersubstringline-breaks

Get the line number of a string from body of text


Let's say I have a file with two lines and I get the indexOf a substring in the file. It returns with 18 the character that the substring is found at. How can I find the line with this information?

var file = [
  'var foo = "hello"',
  'console.log(foo)',
].join('\n')

var char = file.indexOf('console') // => 18
var line = lineOfChar(file, char) // => 2

Solution

  • A possible way to achieve this, is to find the the string like you did with:

    var index = file.indexOf('console'); // => 18
    

    Then use this index to make a substring containing everything before that index:

    var tempString = str.substring(0, index);
    

    And lastly we count the occurrences of \n:

    var lineNumber = tempString.split('\n').length;
    // You should do - 1 if you want your 'first' line to be 0