Reputation: 59365
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
Upvotes: 8
Views: 12753
Reputation: 657
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
Upvotes: 20
Reputation: 5873
function lineOf(text, substring){
var line = 0, matchedChars = 0;
for (var i = 0; i < text.length; i++) {
text[i] === substring[matchedChars] ? matchedChars++ : matchedChars = 0;
if (matchedChars === substring.length){
return line;
}
if (text[i] === '\n'){
line++;
}
}
return -1;
}
Avoids iterating over the string twice, once to find the substring and again to find the newlines.
Upvotes: 2
Reputation: 59365
var assert = require('assert')
var file = [
'var alpha = "hello"',
'var beta = "hello"',
'var gamma = "hello"',
'var delta = "hello"',
'var episilon = "hello"'
].join('\n')
function getLine (body, charOrString) {
if (!body) return false
if (!charOrString) return false
var char = (typeof charOrString === 'string') ? body.indexOf(charOrString) : charOrString
var subBody = body.substring(0, char)
if (subBody === '') return false
var match = subBody.match(/\n/gi)
if (match) return match.length + 1
return 1
}
assert.equal(getLine(file, 'missing'), false)
assert.equal(getLine(file, 'alpha'), 1)
assert.equal(getLine(file, 'beta'), 2)
assert.equal(getLine(file, 'gamma'), 3)
assert.equal(getLine(file, 'delta'), 4)
assert.equal(getLine(file, 'episilon'), 5)
Upvotes: 2