假设我有一个包含两行的文件,我在文件中得到indexOf
个子字符串。它返回18
找到子字符串的字符。如何找到包含此信息的行?
var file = [
'var foo = "hello"',
'console.log(foo)',
].join('\n')
var char = file.indexOf('console') // => 18
var line = lineOfChar(file, char) // => 2
答案 0 :(得分:9)
实现这一目标的一种可能方法是找到与您一样的字符串:
var index = file.indexOf('console'); // => 18
然后使用此索引创建一个包含该索引之前所有内容的子字符串:
var tempString = str.substring(0, index);
最后我们计算\n
:
var lineNumber = tempString.split('\n').length;
// You should do - 1 if you want your 'first' line to be 0
答案 1 :(得分:1)
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;
}
避免迭代字符串两次,一次找到子字符串并再次找到换行符。
答案 2 :(得分:0)
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)