Find the Line and Column Position of Any Character within a String – index-to-position

Category: Javascript | February 28, 2024
Author:sindresorhus
Views Total:1 view
Official Page:Go to website
Last Update:February 28, 2024
License:MIT

Preview:

Find the Line and Column Position of Any Character within a String – index-to-position

Description:

index-to-position is a tiny and fast JavaScript utility designed for developers who need to find the exact line and column position of any character within a string.

The main goal of this library is to convert a string index to its corresponding line and column position. This makes it easy to find the location of a character in a multi-line string.

How to use it:

1. Install and import the index-to-position.

# NPM
$ npm i index-to-position
import indexToPosition from 'index-to-position';
2. The library takes a string and index as input and then counts newlines to determine the line number and character position within each line to find the column number.
indexToPosition('CSS\nScript\n!', 7)

3. The output is a JavaScript object with the discovered line and column numbers (default: zero indexed).

{
  line: 1, // line 2
  column: 3, // column 4
}

4. Determine whether to use 0-based or 1-based indexing. Default: true.

indexToPosition('CSS\nScript\n!', 7, {
  oneBased: true
})

Changelog:

v1.0.0 (02/28/2024)

  • Strictly validate the parameters

You Might Be Interested In:


Leave a Reply