Home  >  Q&A  >  body text

Regular expression to replace several symbols with HTML tags

I'm trying to build a regular expression that replaces all symbols "$$" with some HTML tags, like <someTag></someTag>.

I used this regex, but it doesn't cover all cases:

$$(\S[^\*]+\S)$$
'aaa $3$$ c$ ddd'.replace(/$$(\S[^\*]+\S)$$/g, '<a1></a1>') // works

'aaa $3$$ c$ $$ddd$$'.replace(/$$(\S[^\*]+\S)$$/g, '<a1></a1>') // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'

console.log('aaa $3$$ c$ ddd'.replace(/$$(\S[^\*]+\S)$$/g, '<a1></a1>')) // works

console.log('aaa $3$$ c$ $$ddd$$'.replace(/$$(\S[^\*]+\S)$$/g, '<a1></a1>')) // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'

P粉362071992P粉362071992183 days ago375

reply all(2)I'll reply

  • P粉739886290

    P粉7398862902024-04-02 13:41:43

    Not a regex solution, but it works. Description: Split the string using the delimiter ($$). Then create a new string result and insert each part of the array. It then checks whether the current index is odd or even, and adds a start tag (prefix) or end tag (suffix) as appropriate. I hope this helps!

    function replaceTag(string, delimiter, prefix, suffix){
      
      let parts = string.split(delimiter);
      let result = '';
      
      for(let index = 0; index < parts.length; index++){
      
        result += parts[index];
      
        if(index % 2 == 0 && index < parts.length - 1){
        
          result += prefix;
        
        }
        else if(index < parts.length - 1){
        
          result += suffix;
        
        }
      
      }
      
      return result;
    
    }
    
    console.log(replaceTag('aaa $3$$ c$ ddd', '$$', '', ''));
    console.log(replaceTag('aaa $3$$ c$ $$ddd$$', '$$', '', ''));

    reply
    0
  • P粉592085423

    P粉5920854232024-04-02 09:46:01

    The fastest way is to use the non-greedy point-to-point method: /\$\$(.*?)\$\$/sg
    https://regex101.com/r/upveAX/1
    Using dot alone will always be faster since it doesn't rely on assertions or class structures,
    This adds a 3x performance overhead.

    console.log('aaa $3$$ c$ ddd'.replace(/$$(.*?)$$/sg, ''));
    
    console.log('aaa $3$$ c$ $$ddd$$'.replace(/$$(.*?)$$/sg, ''));

    reply
    0
  • Cancelreply