Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line number of the matched characters in JS/node.js

Is it possible to find the line number of the regex matched characters for multiline inputs (such as files) in Javascript or node.js?

like image 982
Madhusudan.C.S Avatar asked Aug 04 '11 18:08

Madhusudan.C.S


People also ask

What does .match do in JavaScript?

JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.

How do I count the number of lines in JavaScript?

To count number of text lines inside DOM element, we will use the following approach. Obtain the total height of content inside the DOM element. Obtain the height of one line. By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.

What is regex in Nodejs?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.


1 Answers

Thank you @Shanimal I changed your code to also add the column position:

function lineNumberByIndex(index, string) {
  const re = /^[\S\s]/gm;
  let line = 0,
    match;
  let lastRowIndex = 0;
  while ((match = re.exec(string))) {
    if (match.index > index) break;
    lastRowIndex = match.index;
    line++;
  }
  return [Math.max(line - 1, 0), lastRowIndex];
}

const findOccurrences = (needle, haystack) => {
  let match;
  const result = [];
  while ((match = needle.exec(haystack))) {
    const pos = lineNumberByIndex(needle.lastIndex, haystack);
    result.push({
      match,
      lineNumber: pos[0],
      column: needle.lastIndex - pos[1] - match[0].length
    });
  }
  return result;
};

const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.`;
findOccurrences(/dolor/gim, text).forEach(result =>
  console.log(
    `Found: ${result.match[0]} at ${result.lineNumber}:${result.column}`
  )
);
like image 177
EliSherer Avatar answered Nov 01 '22 13:11

EliSherer