Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace brackets to span javascript

I want to manipulate the DOM a bit and need some help.

That's my HTML-Markup:

<span class=“content“> This is my content: {#eeeeee}grey text{/#eeeeee} {#f00000}red text{/#f00000}</span>

That's how it should be:

<span class="content">This is my content: <span style="color:#eeeeee;">grey text</span><span style="color:#f00000;">red text</span></span>

The script should replace the brackets with span tags to change the font-color. The color should the same that is in the bracket.

My approach:

function regcolor(element) {
    var text = element.innerText;
    var matches = text.match(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim);
    if (matches != null) {
        var arr = $(matches).map(function (i, val) {
            var input = [];
            var color = val.slice(1, 8);
            var textf = val.slice(9, val.length - 10);
            var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
            input.push(html);
            return input;
        });

        var input = $.makeArray(arr);

        $(element).html(input.join(''));
    };

But it's not working very well and i'm not feeling good with the code, it looks messy. And the script looses the content that's not in the brackets("This is my content:").

Anyone a idea?

like image 972
Priya Sharma Avatar asked May 08 '26 02:05

Priya Sharma


1 Answers

I've used just a touch of jQuery, but it could easily do without. It's just a regular expression string replacement.

$('.content').each(function() {
  var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g;
  //          ^                 ^
  //          $1                $2

  this.innerHTML = this.innerHTML.replace(re, function($0, $1, $2) {
    return '<span style="color: ' + $1 + '">' + $2 + '</span>';
  });
});

I'm using a back-reference to properly match the opening and closing braces.

Update

Could be even shorter:

$('.content').each(function() {
  var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
  repl = '<span style="color: $1">$2</span>';

  this.innerHTML = this.innerHTML.replace(re, repl);
});

Look mum, no jQuery

var nodes = document.getElementsByClassName('content');

for (var i = 0, n = nodes.length; i < n; ++i) {
  var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
  repl = '<span style="color: $1">$2</span>';

  nodes[i].innerHTML = nodes[i].innerHTML.replace(re, repl);
}
like image 191
Ja͢ck Avatar answered May 10 '26 16:05

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!