Get Off My Lawn Get Off My Lawn - 3 months ago 5x
Javascript Question

Get a line in a string at a particular offset

I have a string that I am looping through character by character. I know the offset of the character in the string but I don't know the line.

What I would like to do is get the line text at a particular offset. how can I do so?

I like to
eat pizza
do you?

For the above example, If I want the line at offset
I would get the following line
eat pizza


Here's my implementation (

function findLine(str, idx) {
  var first = str.substring(0, idx);
  var last = str.substring(idx);

  var firstNewLine = first.lastIndexOf("\n");

  var secondNewLine = last.indexOf("\n");

  if ( secondNewLine == -1 ) {
    secondNewLine = last.length;

  return str.substring(firstNewLine+1, idx+secondNewLine);

var str =
`I like to 
eat pizza
do you?`;
console.log(findLine(str, 15));