Is it possible to find the line number of the regex matched characters for multiline inputs (such as files) in Javascript or node.js?
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.
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.
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.
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}`
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With