Skip to content

Instantly share code, notes, and snippets.

@flockast
Created September 22, 2021 18:19
Show Gist options
  • Save flockast/bfa6252e7598e17b4fe68f628189e0b4 to your computer and use it in GitHub Desktop.
Save flockast/bfa6252e7598e17b4fe68f628189e0b4 to your computer and use it in GitHub Desktop.
Replace wrapping symbols on tags
export const escape = (string) => string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
export const replaceSymbolOnTag = (str, symbol, tagName) => {
const regexp = new RegExp(`${escape(symbol)}(.*?)${escape(symbol)}`, 'gi')
return str.replace(regexp, `<${tagName}>$1</${tagName}>`)
}
export const replacer = (selectors = [], symbol = '#', tagName = 'span') => {
const $elements = []
selectors.forEach((selector) => {
$elements.push(...Array.from(document.querySelectorAll(selector)))
})
$elements.forEach(($element) => {
$element.innerHTML = replaceSymbolOnTag($element.innerHTML, symbol, tagName)
})
}
import { replaceSymbolOnTag, replacer } from './formatter'
// Working with string
replaceSymbolOnTag('hello *world*', '*', 'b') // hello <b>world</b>
replaceSymbolOnTag('hello _world_', '_', 'i') // hello <i>world</i>
replaceSymbolOnTag('hello ~world~', '~', 's') // hello <s>world</s>
replaceSymbolOnTag('hello #world#', '#', 'span') // hello <span>world</span>
// Working with html selectors
replacer(['.title', '.article'], '#', 'span')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment