Get Off My Lawn Get Off My Lawn - 4 months ago 6
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
15
I would get the following line
eat pizza
.

Answer

Here's my implementation (https://jsfiddle.net/Lgb3qncu/1/):

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));

Comments