Joram Joram - 1 month ago 6
CSS Question

Replace tags without an ending tag with span

I want to do something that probably is not possible, but here goes nothing.

Let's say I have this dummy text: "{red}Test {default}Message" (without quotation marks)
I would like a (jQuery) script to replace the {red} with a span and add a closing tag. the P element would be where the formatted test message would be.

E.G.

<p><span style="color:red;">Test</span> <span style="color:white;">Message</span></p>


I've searched all over the internet and I could only find HTML elements getting replaced with other HTML elements. (Or similar to that).
I haven't tried something yet, because I have no idea where to start.

Answer

Note: use initial color instead of default.

s = "{red}Test {initial}Message";
html = '<p>'+s.replace(/\{(\w*)\}([^{]*)/g,'<span style="color:$1">$2</span>')+'</p>'

document.body.innerHTML=html;
// inherit
s = "<br>{red}Red {initial}Initial and {inherit}Inherited colors";
html = '<p style="color:orange">'+s.replace(/\{(\w*)\}([^{]*)/g,'<span style="color:$1">$2</span>')+'</p>'

document.body.innerHTML+=html;
//with own colors
colors={
  red:'#5f0',
  green:'purple'
};
s = "<br>{red}Red {green}Green and {orange}orange colors";
html = '<p>'+s.replace(/\{(\w*)\}([^{]*)/g,function(s,s1,s2){
  if(colors[s1])
    s1=colors[s1];
  return '<span style="color:'+s1+'">'+s2+'</span>'
})+'</p>'

document.body.innerHTML+=html;