JSFiddle - React, Tailwind, and code Playground
by brigand
JavaScript
const s = 'ππ meπoπw π';
const re = /[eow]+/gu;
const toSpan = (color, text) => {
const span = document.createElement('span')
span.style.background = color
span.textContent = text;
return span;
}
const ranges = [];
s.replace(re, (match, ...args) => {
args.pop();
const pointIndex = args.pop();
const index = [...s.slice(0, pointIndex)].length;
const length = [...match].length
ranges.push([index, index + length]);
})
function inRanges(index) {
for (const [start, end] of ranges) {
if (index >= start && index < end) {
return true
}
}
return false
}
console.log(ranges)
const out = document.createElement('pre')
for (const [index, char] of [...s].entries()) {
const color = inRanges(index) ? '#99ff99' : '#ff9999'
out.appendChild(toSpan(color, char))
}
document.body.appendChild(out)