2013-02-22 120 views
3

我想操縱DOM一點,需要一些幫助。將括號替換爲span javascript

這是我的HTML標記:

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

這是應該的:

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

的腳本應該以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('')); 
    }; 

但它不工作非常好,我感覺不良好的代碼,它看起來凌亂。 腳本丟失了不在括號內的內容(「這是我的內容:」)。

任何想法?

+0

您是否計劃嵌套托架塊?像{{}}一些文字{第二}這裏{/第二} {/第一}' – TheBronx 2013-02-22 09:32:40

回答

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>'; 
    }); 
}); 

我正在使用反向引用來正確地匹配打開和關閉大括號。

更新

可能會更短:

$('.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); 
}); 

看媽媽,沒有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); 
} 
+0

謝謝,它的工作:) – 2013-02-23 08:47:18

1

使用正則表達式來直接替換匹配:

function regcolor2(element) { 
    var text = element.html(); 
    var i = 0; 
    var places = text.replace(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim, function(match) { 
     var color = match.slice(1, 8); 
     var textf = match.slice(9, match.length - 10); 
     var html = "<span style=\"color: " + color + ";\">" + textf + "</span>"; 
     return html; 
    }); 

    $(element).html(places); 
} 
1

它可以使用jQuery短,這種方法或語法

$(function() { 

$('.content').html($('.content').text().replace(new RegExp('{(.*?)}(.*?){\/.*?}','g'), '<span style="color:$1">$2</span>')); 

});