2012-02-28 38 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>'); 
相关问题