Skip to content
Advertisement

How do i find character position (row, col) in multi-line string?

How i can find position of current character in multi-line string? If every line in a string was the same length it would be easy. E.g.

const str = `hello
hello
hello`

const findPos = (str, ind) => {
  const [cols] = str.split('n');
  return { row: ind / cols.length | 0, col: ind % cols.length };
};

findPos(str, 12) // { row: 2, col: 2 }

But how can i do it, if every row is different length? E.g.

const str = `hello
from
my
old
friend!`

findPos(str , 12) // { row: 3, col: 1 }

Advertisement

Answer

Use a while loop to iterate over the split lines, subtracting the length of the current line from the number of characters to go. If the length is shorter than the number of characters to go, return the characters to go as the col, and the number of lines iterated over as the row:

const findPos = (input, indexToFind) => {
  const lines = input.split('n');
  let charsToGo = indexToFind;
  let lineIndex = 0;
  while (lineIndex < lines.length) {
    const line = lines[lineIndex];
    const char = line[charsToGo];
    if (char) {
      return { row: lineIndex, col: charsToGo };
    }
    charsToGo -= line.length;
    lineIndex++;
  }
  return 'None';
};

const str = `hello
from
my
old
friend!`

console.log(findPos(str , 12)); // { row: 3, col: 1 }

Note that this does not consider the newlines as characters to be iterated over, which seems to be in line with your expected output. For an example of this generating a position for all characters in the string see the following snippet:

const findPos = (input, indexToFind) => {
  const lines = input.split('n');
  let charsToGo = indexToFind;
  let lineIndex = 0;
  while (lineIndex < lines.length) {
    const line = lines[lineIndex];
    const char = line[charsToGo];
    if (char) {
      return { row: lineIndex, col: charsToGo };
    }
    charsToGo -= line.length;
    lineIndex++;
  }
  return 'None';
};

const str = `hello
from
my
old
friend!`

const lenWithoutNewlines = str.length - str.match(/n/g).length;
for (let i = 0; i < lenWithoutNewlines; i++) {
  console.log(findPos(str , i));
}
Advertisement