Regular expression to replace several symbols with HTML tags
P粉362071992
P粉362071992 2024-04-01 21:01:01
0
2
535

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粉362071992
P粉362071992

reply all(2)
P粉739886290

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 ', ''));
console.log(replaceTag('aaa $3$$ c$ $$ddd$$', '$$', '', ''));
P粉592085423

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, ''));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template