Skip to content

Instantly share code, notes, and snippets.

@kotarok
Last active August 16, 2025 06:34
Show Gist options
  • Save kotarok/93794acfa5225d97206908ecf76f2411 to your computer and use it in GitHub Desktop.
Save kotarok/93794acfa5225d97206908ecf76f2411 to your computer and use it in GitHub Desktop.
Simple text markup function
/**
* Simple text markup function
* @param {string} selector - CSS selector
* @param {string} chars - Character class pattern
* @param {string|Object|Function} processor - Class name, attributes object, or custom function
*/
const markupText = (selector, chars, processor) => {
const regex = new RegExp(`[${chars}][${chars}\\s]*[${chars}]?`, 'g')
let process
if (typeof processor === 'string') {
process = () => ({ tag: 'span', class: processor, lang: 'en' })
} else if (typeof processor === 'function') {
process = processor
} else {
process = () => ({ tag: 'span', ...processor })
}
document.querySelectorAll(selector).forEach((el) => {
el.childNodes.forEach((node) => {
if (node.nodeType === 3) {
const html = node.textContent.replace(regex, (match) => {
if (/^\d+$/.test(match)) return match
const result = process(match)
const { tag = 'span', ...attrs } = result.attributes || result
const attrStr = Object.entries(attrs)
.map(([k, v]) => ` ${k}="${v}"`)
.join('')
return `<${tag}${attrStr}>${match}</${tag}>`
})
if (html !== node.textContent) {
const temp = document.createElement('div')
temp.innerHTML = html
node.replaceWith(...temp.childNodes)
}
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment