2012-02-28 26 views
0

我有一個HTML字符串(不是DOM元素),如:在一個HTML字符串跨度類替換一些innerTexts和發佈回DOM

<p>This is a sample dataa<p> 
    <img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img> 

我需要追加<span class="spellerror"></span>到有問題的話,並也只需要檢查和附加文本內容。

<p>This is a sample dataa<p> 
    <img src="Randomz" alt="Randomz Image"><span class="spellerror"> Randomz </span> is the name of the image</img> 

我的問題是,這是一個HTML和正則表達式的混合。是否有可能:

  1. 爲了使某種DOM元素,然後工作呢?
  2. 或者是否有正則表達式來實現這一點。

我不想觸摸屬性,如果我修改文本內容,我該如何發佈回去......因爲我需要在那裏插入一些HTML。

+0

我需要rephasize我只有一個HTML字符串,而不是一個DOM元素。所以任何DOM方法都不會直接有意義,除非我將它們轉換爲該結構。 – Nishant 2012-02-28 13:42:58

回答

1

我不喜歡這個解決方案,但它的工作原理:

'<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>' 
    .match(/<[^>]+>|[^<]+|<\/[^>]+>/g) 
    .map(function (text, index) { 
     if (index === 1) { 
      return text.replace(/(Randomz)/, '<span class="spellerror">$1</span>'); 
     } else { 
      return text; 
     } 
    }) 
    .join(''); 

正則表達式分成打開標籤的innerText,關閉標籤。 然後迭代所有成員,如果它的innerText,它將替換爲所需的文本 然後加入。

林史迪威想嘗試的東西少往返約但那是我的一切

+0

好吧,我剛剛意識到這個缺陷,因爲它也alt標籤,我會更新在2分鐘 – 2012-02-28 14:01:41

+0

不會取代每個字的存在?例如,甚至一個屬性。我不需要那個。僅文本內容。 – Nishant 2012-02-28 14:01:46

+0

@Nishant,我更新了我的答案 – 2012-02-28 14:17:19

1

使用某種形式的模板的:

String.prototype.template = String.prototype.template || 
     function(){ 
      var args = Array.prototype.slice.call(arguments) 
       ,str = this 
      ; 
      function replacer(a){ 
       var aa = Number(a.substr(1))-1; 
       return args[aa]; 
      } 
      return str.replace(/(\$\d+)/gm,replacer); 
}; 
var thestring = [ '<p>This is a sample dataa</p><img src="Randomz"' 
        ,' alt="Randomz Image">$1Randomz$2 ' 
        ,'is the name of the image</img>'].join('') 
    ,nwString = theString.template('<span class="spellerror">','</span>'); 
相關問題