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.

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript
Advertisement