Created
          September 22, 2021 18:19 
        
      - 
      
 - 
        
Save flockast/bfa6252e7598e17b4fe68f628189e0b4 to your computer and use it in GitHub Desktop.  
    Replace wrapping symbols on tags
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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) | |
| }) | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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