convert to javascript: class Highliter
{
protected wheresearch;protectedany_patterns;
code
Assistant
User
in string_replace_run don't use RegExp, use sub string method
Assistant
Got it! Here is an updated version of string_replace_run() that does not use RegExp and instead uses plain string methods (indexOf, slice) to replace all occurrences of each pattern with the styled replacement.
javascript
string_replace_run() {
const data = this.search_for_replace();
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
const replacement = data.ready_for_replace_style[index];
let startIndex = 0;
while (true) {
const foundIndex = res.indexOf(pattern, startIndex);
if (foundIndex === -1) break;
// Replace by reconstructing the string:
res = res.slice(0, foundIndex) + replacement + res.slice(foundIndex + pattern.length);
// Move startIndex forward to avoid infinite loop
startIndex = foundIndex + replacement.length;
}
});
return res;
}
User
use text.replace
Assistant
If you want to use String.prototype.replacewithout regex (i.e., literal substring replacement) there’s a trick: you pass the substring as the first argument, and it replaces only the first occurrence.
To replace all occurrences without regex, you normally have to do a loop or use a regex with the global flag.
But since you want to avoid regex altogether, the reliable way is to repeatedly replace first occurrence until none left:
javascript
string_replace_run() {
const data = this.search_for_replace();
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
const replacement = data.ready_for_replace_style[index];
// Replace all occurrences without regex:
while (res.includes(pattern)) {
res = res.replace(pattern, replacement);
}
});
return res;
}
User
why "while"?
Assistant
Great question!
Why use a while loop here?
str.replace(substring, replacement) replaces only the first occurrence of substring in the string.
So if the substring appears multiple times, a single call to replace won't replace them all.
The while loop repeats the replace operation until the substring no longer exists in the string.
Here's a JavaScript version of your PHP Highliter class, converted with similar structure and functionality. For logging, I've used console.log instead of NewLogger::info. Since JavaScript regex handling differs from PHP's in some ways (especially no direct equivalent of preg_replace with arrays), I've adapted the logic accordingly.
javascript
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));
// 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;
}
string_replace_run() {
const data = this.search_for_replace();
// Simple replace all occurrences of each pattern with corresponding span style
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
// Escape special regex characters in pattern to safely use in RegExp
const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escapedPattern, 'g');
res = res.replace(regex, data.ready_for_replace_style[index]);
});
return res;
}
regex_replace_run() {
const data = this.search_for_replace();
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 = [];
// 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;
const res = (() => {
let result = 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 = result.replace(regex, data.ready_for_replace_style[index]);
});
return result;
})();
return res;
}
}
Notes:
In JavaScript, regex patterns are specified as RegExp objects. The input $any_patterns in PHP was an associative array with regex strings as keys — I assumed in JS it's an object like { '/pattern/g': 'className' }.
PHP's preg_match_all with PREG_SET_ORDER is mimicked by looping over regex matches manually with RegExp.exec() in a loop.
Match replacement uses standard JS string replace with global regexes.
The PHP method of wrapping patterns in word boundaries (\b) is emulated via regex in regex_replace_run.
The lookbehind support in JavaScript (regex_replace_run_lookbehind) requires modern JS engines (ES2018+). The lookbehind pattern was simplified due to complexity of PHP pattern.
To test Highliter, pass strings and an object of patterns, e.g.:
Let me know if you'd like me to help with adapting the input format or adding helper utilities!
Explanation:
For each pattern:
We search for the pattern using indexOf.
When found, we rebuild the string with the part before the match + replacement + the part after the match.
Increase startIndex to continue search after the replacement, to avoid infinite loops or replacing the newly inserted HTML.
This ensures all occurrences are replaced without using regex.
If you want the full class snippet with this function replaced, let me know!
Explanation:
String.prototype.replace with a string argument replaces only the first occurrence.
By looping while res.includes(pattern), we repeatedly replace the first occurrence until none remain.
This avoids regex and uses only string methods.
Let me know if you want me to provide the full updated class with this included!
let text = "foo bar foo baz foo";
text = text.replace("foo", "<span>foo</span>");
console.log(text);
// Output: "<span>foo</span> bar foo baz foo"
// Only the first 'foo' was replaced.
while (text.includes("foo")) {
text = text.replace("foo", "<span>foo</span>");
}
console.log(text);
// Output: "<span>foo</span> bar <span>foo</span> baz <span>foo</span>"
Without the loop, only one occurrence would be replaced.
Alternative: Why not use split + join?
Another way to replace all occurrences without regex is:
js
text = text.split(pattern).join(replacement);
This replaces all occurrences at once.
Summary
while + replace loop: repeatedly replace the first occurrence until none left.
Or split(pattern).join(replacement): directly replace all occurrences without loop or regex.
So if you want simpler and efficient way without regex, this is better:
js
string_replace_run() {
const data = this.search_for_replace();
let res = data.where_search;
data.ready_all_patterns.forEach((pattern, index) => {
const replacement = data.ready_for_replace_style[index];
res = res.split(pattern).join(replacement);
});
return res;
}
Let me know if you'd like me to adjust the class using this approach!