获取指定行和列的文本
Get the text at the specified row and column
如果我有这样的字符串:
const string = [
'some text here',
'some more text here',
'more more more text here',
'just for some variety here'
].join('\n')
如果我有起始行号和列号,以及结束行号和列号,我怎样才能得到这些点的文本?
例如,如果行号数据是:
const lineData = {
start: {row: 2, column: 5},
end: {row: 3, column: 4}
}
我应该得到 'more text here\nmore'
这里我写了一个解决方案。我已将您的 string
数组转换为 2D
数组,并将字符从头到尾连接起来。关注这个-
const string = [
'some text here',
'some more text here',
'more more more text here',
'just for some variety here'
];
const string2d = string.map(line => line.split(''));
const lineData = {
start: {row: 2, column: 5},
end: {row: 3, column: 4}
}
const {start: {row: startRow, column: startColumn}, end: {row: endRow, column: endColumn}} = lineData;
let ans = '';
// Run from start row to the end row
for (let i = startRow - 1; i <= endRow - 1; i++) {
let j = 0;
// For the first row the column starts from the start column
// And the other cases it starts from 0
if (i === startRow - 1) {
j = startColumn - 1;
}
// Concat the characters from j to length of the line.
// But for the endRow line concat to the end column
while (j < string2d[i].length) {
ans += string2d[i][j];
j++;
if (i === endRow - 1 && j > endColumn) break;
}
// Append a newline after every line
ans += "\n";
}
console.log(ans);
如果我有这样的字符串:
const string = [
'some text here',
'some more text here',
'more more more text here',
'just for some variety here'
].join('\n')
如果我有起始行号和列号,以及结束行号和列号,我怎样才能得到这些点的文本?
例如,如果行号数据是:
const lineData = {
start: {row: 2, column: 5},
end: {row: 3, column: 4}
}
我应该得到 'more text here\nmore'
这里我写了一个解决方案。我已将您的 string
数组转换为 2D
数组,并将字符从头到尾连接起来。关注这个-
const string = [
'some text here',
'some more text here',
'more more more text here',
'just for some variety here'
];
const string2d = string.map(line => line.split(''));
const lineData = {
start: {row: 2, column: 5},
end: {row: 3, column: 4}
}
const {start: {row: startRow, column: startColumn}, end: {row: endRow, column: endColumn}} = lineData;
let ans = '';
// Run from start row to the end row
for (let i = startRow - 1; i <= endRow - 1; i++) {
let j = 0;
// For the first row the column starts from the start column
// And the other cases it starts from 0
if (i === startRow - 1) {
j = startColumn - 1;
}
// Concat the characters from j to length of the line.
// But for the endRow line concat to the end column
while (j < string2d[i].length) {
ans += string2d[i][j];
j++;
if (i === endRow - 1 && j > endColumn) break;
}
// Append a newline after every line
ans += "\n";
}
console.log(ans);