refactor code, deside use class or only function: class Highliter {
constructor(where_search, any_patterns) {
this.where_search = where_search;
this.any_patterns = any_patterns; // expected as an object { regex: className }
}
search_for_replace() {
// mimic json encode/decode safely by cloning string (redundant in JS but keeping structure)
let where_search = JSON.parse(JSON.stringify(this.where_search));
code
// replace new lines with spaces
where_search = where_search.replace(/\n/g, ' ');
console.log(JSON.stringify(["any_patterns", this.any_patterns]));
console.log(JSON.stringify(["where_search", where_search]));
const ready_all_patterns = [];
const ready_for_replace_style = [];
for (const [patternStr, className] of Object.entries(this.any_patterns)) {
// Create RegExp object from string pattern
//(assume patternStr includes delimiters and
//flags like "/pattern/gi")
// Remove slashes and parse flags manually:
const match = patternStr.match(/^\/(.+)\/([gimsuy]*)$/);
if (!match) continue; // skip invalid patterns
const [_, patternBody, flags] = match;
const regex = new RegExp(patternBody, flags);
// Find all matches
let matchArray;
while ((matchArray = regex.exec(where_search)) !== null) {
const for_replace = matchArray[0];
const what_search_for_replace = for_replace;
const replace_style = `<span class='${className}'>${for_replace}</span>`;
if (!ready_all_patterns.includes(what_search_for_replace)) {
ready_all_patterns.push(what_search_for_replace);
ready_for_replace_style.push(replace_style);
}
// Avoid infinite loop if zero width match:
if (regex.lastIndex === match.index) {
regex.lastIndex++;
}
}
}
const res = {
ready_all_patterns,
ready_for_replace_style,
where_search,
};
// console.log("search_for_replace(), ", JSON.stringify(res));
return res;
Assistant
}
string_replace_run() {
const data = this.search_for_replace();
let res = data.where_search;
code
data.ready_all_patterns.forEach((pattern, index) => {
const replacement = data.ready_for_replace_style[index];
while (res.includes(pattern)) {
//Without the loop, only one occurrence would be replaced.
res = res.replace(pattern, replacement);
}
});
return res;
}
regex_replace_run() {
const data = this.search_for_replace();
code
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
// Using word boundaries like in PHP: /\bpattern\b/
const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b${escapedPattern}\\b`, 'g');
res = res.replace(regex, data.ready_for_replace_style[index]);
});
// console.log(JSON.stringify(["Result from regex_replace_run:", res]));
return res;
}
regex_replace_run_lookbehind() {
const data = this.search_for_replace();
const new_style = [];
code
// Adjust styles if they contain $ character
for (let style of data.ready_for_replace_style) {
if (style.includes('$')) {
style = style.replace(/\$/g, '\\$').replace('</span>', '') + '</span>';
}
new_style.push(style);
}
data.ready_for_replace_style = new_style;
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
let safePattern = pattern;
let regex;
if (pattern.includes('$')) {
safePattern = safePattern.replace(/\$/g, '\\$').replace(/\./g, '\\.');
// pattern for negative lookbehind (note: JS supports fixed length lookbehind in latest versions)
// Adjust lookbehind pattern if needed (adjust string as per your original logic)
const lookbehind = '(?<!par\\s{1,3}value\\s{1,3})';
regex = new RegExp(lookbehind + safePattern, 'g');
} else {
// if you want to fallback to matching as is if no '$'
regex = new RegExp(safePattern, 'g');
}
result = res.replace(regex, data.ready_for_replace_style[index]);
});
return res;
}
}
The existing design uses a class Highliter to encapsulate the functionality and state. This is a reasonable choice if you expect to:
Create multiple separate highlighter instances each with different source text and patterns;
Possibly extend the class with additional methods later on;
Maintain intermediate state or cache results inside the instance.
If the use case is simpler — say, a single one-off invocation to highlight text using static patterns — then a pure functional approach might be simpler and more idiomatic.
Recommendation:
Keep the class if: you want to maintain state, create multiple highlighters, or extend later.
Use only functions if: you just want one simple function call that takes text + patterns and returns highlighted text.
Refactoring the current class version:
I will keep the class but clean up the code by:
Removing unnecessary cloning of strings;
Clarifying method names and comments;
Avoiding redundant arrays and loops;
Using replace with RegExp and replacer function to handle replacements cleanly;
Fixing the last method regex_replace_run_lookbehind (you had a result variable assigned but never used, and logic seemed incomplete);
Adding some input validation;
Adding some helper functions.
js
class Highlighter {
/**
* @param {string} text - The input text where patterns are searched.
* @param {Object} patterns - Object mapping regex string ("/pattern/flags") to className.
*/
constructor(text, patterns) {
this.text = text.replace(/\n/g, ' '); // normalize newlines to spaces
this.patterns = patterns;
}
/**
* Parses the pattern strings from the form "/pattern/flags" to RegExp.
* @returns {Array<{regex: RegExp, className: string}>}
*/
getRegexes() {
const regexes = [];
for (const [patternStr, className] of Object.entries(this.patterns)) {
const match = patternStr.match(/^\/(.+)\/([gimsuy]*)$/);
if (!match) {
// ignore invalid pattern strings
continue;
}
const [, patternBody, flags] = match;
try {
regexes.push({ regex: new RegExp(patternBody, flags), className });
} catch {
// Skip invalid regexes
}
}
return regexes;
}
/**
* Finds all unique matched substrings and corresponding replacement spans.
* Returns an array of {matchedText, replacement}.
*/
findMatches() {
const regexes = this.getRegexes();
const uniqueMatches = new Map();
for (const { regex, className } of regexes) {
// Reset lastIndex in case RegExp is global:
regex.lastIndex = 0;
// Iterate all matches
let match;
while ((match = regex.exec(this.text)) !== null) {
const matchedText = match[0];
if (!uniqueMatches.has(matchedText)) {
uniqueMatches.set(
matchedText,
`<span class='${className}'>${matchedText}</span>`
);
}
// Prevent infinite loop on zero-width matches
if (regex.lastIndex === match.index) regex.lastIndex++;
}
}
return [...uniqueMatches.entries()].map(([matchedText, replacement]) => ({ matchedText, replacement }));
}
/**
* Replace occurrences using simple string replace (multiple times for all).
* This method can be slow for large texts.
*/
replaceByString() {
let result = this.text;
const matches = this.findMatches();
for (const { matchedText, replacement } of matches) {
// Replace all occurrences using loop + string replace
while (result.includes(matchedText)) {
result = result.replace(matchedText, replacement);
}
}
return result;
}
/**
* Replace occurrences using regex with word boundaries.
* Matches only whole words exactly equal to matched text.
*/
replaceByRegexWordBoundary() {
let result = this.text;
const matches = this.findMatches();
for (const { matchedText, replacement } of matches) {
const escaped = matchedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b${escaped}\\b`, 'g');
result = result.replace(regex, replacement);
}
return result;
}
/**
* Replace occurrences with support for lookbehind (ES2018+).
* Currently assumes patterns containing '$' need special handling.
*/
replaceWithLookbehind() {
let result = this.text;
const matches = this.findMatches();
for (const { matchedText, replacement: rawReplacement } of matches) {
// Escape $ in replacement to avoid issues if used in replacement string
const replacement = rawReplacement.replace(/\$/g, '\\$');
let regex;
if (matchedText.includes('$')) {
// Example: negative lookbehind for 'par value ' before pattern
// Adjust this condition per your need
const escapedPattern = matchedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const lookbehind = '(?<!par\\s{1,3}value\\s{1,3})';
regex = new RegExp(lookbehind + escapedPattern, 'g');
} else {
// No lookbehind, match all occurrences
const escaped = matchedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
regex = new RegExp(escaped, 'g');
}
result = result.replace(regex, replacement);
}
return result;
}
}
Usage example:
js
const text = `Some example with patterns.
Let's highlight words and \$dollar_sign, for example.`;
const patterns = {
'/example/gi': 'highlight-example',
'/\\$dollar_sign/': 'highlight-dollar',
};
const highlighter = new Highlighter(text, patterns);
console.log(highlighter.replaceByString());
console.log(highlighter.replaceByRegexWordBoundary());
console.log(highlighter.replaceWithLookbehind());
If you want a pure function style:
js
/**
* Highlights text by patterns given.
* @param {string} text - Input text
* @param {Object} patterns - Object mapping regex string "/pattern/flags" => className
* @returns {string} highlightedText
*/
function highlightText(text, patterns) {
text = text.replace(/\n/g, ' ');
const regexes = Object.entries(patterns).map(([patternStr, className]) => {
const match = patternStr.match(/^\/(.+)\/([gimsuy]*)$/);
if (!match) return null;
const [, patternBody, flags] = match;
try {
return { regex: new RegExp(patternBody, flags), className };
} catch {
return null;
}
}).filter(Boolean);
for (const { regex, className } of regexes) {
text = text.replace(regex, match => `<span class="${className}">${match}</span>`);
}
return text;
}
This is simpler, but loses the multiple options of replacement algorithms.
Summary:
For complex multi-step processing and reuse, keep the class.
Otherwise, use a simple pure function with a single replace pass.
I recommend keeping the class but refactoring as above for clarity and correctness.