Skip to content

Instantly share code, notes, and snippets.

@akiva
Created December 4, 2014 09:31
Show Gist options
  • Save akiva/25ab21f9c858548bd6fe to your computer and use it in GitHub Desktop.
Save akiva/25ab21f9c858548bd6fe to your computer and use it in GitHub Desktop.
// Find which line number a 0-based index falls on by splitting a line
// of text delimited by '\n'
function getLineNumberByCharIndex(index) {
var TEXT = 'abc\ndef\nghijkl\nmnop';
var line = 0;
var i;
for (i = 0; i <= index; i++) {
if (TEXT[i] === '\n') line++;
}
return line;
}
// => 3, 0, 1, 2
console.log(
getLineNumberByCharIndex(14),
getLineNumberByCharIndex(0),
getLineNumberByCharIndex(4),
getLineNumberByCharIndex(8)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment