替换括号以跨越javascript

Pri*_*rma 3 html javascript regex jquery colors

我想稍微操纵DOM并需要一些帮助.

那是我的HTML标记:

<span class=“content“> This is my content: {#eeeeee}grey text{/#eeeeee} {#f00000}red text{/#f00000}</span>
Run Code Online (Sandbox Code Playgroud)

它应该是这样的:

<span class="content">This is my content: <span style="color:#eeeeee;">grey text</span><span style="color:#f00000;">red text</span></span>
Run Code Online (Sandbox Code Playgroud)

该脚本应使用span标记替换括号以更改字体颜色.颜色应与括号中的颜色相同.

我的方法:

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(''));
    };
Run Code Online (Sandbox Code Playgroud)

但是效果并不好,我对代码感觉不好,看起来很乱.并且脚本丢失了不在括号中的内容("这是我的内容:").

有人有想法吗?

Ja͢*_*͢ck 6

我只使用了一点jQuery,但它可以很容易地没有.它只是一个正则表达式字符串替换.

$('.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>';
  });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用反向引用来正确匹配开始和结束括号.

更新

可能更短:

$('.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);
});
Run Code Online (Sandbox Code Playgroud)

看起来妈妈,没有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);
}
Run Code Online (Sandbox Code Playgroud)