Created
December 4, 2014 09:31
-
-
Save akiva/25ab21f9c858548bd6fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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