If I have a string like so:
const string = [
'some text here',
'some more text here',
'more more more text here',
'just for some variety here'
].join('\n')
And if I have a start line number and column number, and an end row number and column number, how can I get the text at those points?
For example, if the line number data was:
const lineData = {
start: {row: 2, column: 5},
end: {row: 3, column: 4}
}
I should get 'more text here\nmore'
Here I've written a solution. I've converted your string
array into a 2D
array and concatenated the characters from start to end. Follow this-
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);