var g="#哈哈#,这话笑#死人#了"
var re = new RegExp("#([^#].)#", "ig")
var te=g.replace(re, "#<a href=\"?key=$1\">$1</a>#")如上面代码,将##包含的文字变成有链接的关键字。因为编码是utf-8的,所以链接中的文字需要转码。即"#<a href=\"?key=$1\">$1</a>#" 中的$1需要转码。如果我使用 "#<a href=\"?key="+encodeURIComponent("$1")+"\">$1</a>#"),转换的并不是哈哈或者死人两词而是$1(我想过使用re.test(g),再取出定义变量赋值RegExp.$1,这样不循环的情况下只能正确转换第一个)请教高手,在不改变 var te=g.replace(re, "#<a href=\"?key=$1\">$1</a>#") 基本格式的情况下,怎么才能对$1进行转码呢?

解决方案 »

  1.   

    试试"#<a href=\"?key=encodeURIComponent('$1')\">$1</a>#"),
      

  2.   

    1."#<a href=\"?key="+encodeURIComponent('$1')+"\">$1</a>#"
    2."#<a href=\"?key=encodeURIComponent('$1')\">$1</a>#"
    第1种情况是转换的$1这个字符,而不是$1所代表的值
    第2种,看看就知道不行了!
      

  3.   

    我想楼主需要的是这样:
    var g="#哈哈#,这话笑#死人#了"
    var re = new RegExp("#([^#].)#", "ig")
    var te=g.replace(re, function($0, $1) {
        return "#<a href=\"?key=" + encodeURIComponent($1) + "\">" + $1 + "</a>#"
    })
    alert(te);
      

  4.   

        var g="#哈哈#,这话笑#死人#了"
    var re = new RegExp("#([^#].)#", "ig")
    var te=g.replace(re, function($1){
        return "#<a href=\"?key="+encodeURIComponent($1)+"\">"+$1+"</a>#"
    });
    alert(te);
      

  5.   

    简化一下,用正则字面量
    没有字母,所以i忽略大小写没有意义,用g就好了。var g = "#哈哈#,这话笑#死人#了";
    var te = g.replace(/#([^#].)#/g, function($0, $1) {
        return "#<a href=\"?key=" + encodeURIComponent($1) + "\">" + $1 + "</a>#"
    });
    alert(te);