2014-01-22 170 views
0

我試圖在這種情況下替換,所有的條件都從jquery中得到。在全球範圍內替換javascript

來源是:1 is expansive than 2.,我需要得到的結果爲Apple is expansive than Pear.c=c.replace(/b/gi,a);不起作用。如何正確寫入?

<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script> 
<script type="text/javascript"> 
    jQuery(document).ready(function(){ 
     var c=$('#source').html(); 
     $('span').each(function(){ 
      var a=$(this).html(); 
      var b=$(this).attr('dir'); 
      c=c.replace(/b/gi,a); 
     }); 
     $('#result').html(c); 
    }); 
</script> 
<div id="source">1 is expansive than 2.</div> 
<span dir="1" style="display:none;">Apple</span> 
<span dir="2" style="display:none;">Pear</span> 
<div id="result"></div> 

回答

0

你必須使用RegExp對象:

var myRegExp = new RegExp(b,'gi'); 
c = c.replace(myRegExp, a); 
0
jQuery(document).ready(function(){ 
     var c=$('#source '); 
     $('span').each(function(){ 
     var a=$(this).html(); 
     var b=$(this).attr('dir'); 
     var r= new RegExp(b, "gi") ; 
     c=c.replace(r,a); 
     }); 
     $('#result').html(c); 
    });