javascript取代全球情况

时间:2014-01-22 14:11:55

标签: javascript regex

我试图在这种情况下替换,所有条件都来自jquery。

来源是: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>

2 个答案:

答案 0 :(得分:0)

您必须使用RegExp对象:

var myRegExp = new RegExp(b,'gi');
c = c.replace(myRegExp, a);

答案 1 :(得分: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);
    });