在JavaScript中替换函数按变量

时间:2018-02-07 18:24:23

标签: javascript random str-replace

我需要用Random替换$我该怎么办呢。 我想将Some texte here some text here中的此文字转换为此Som(gb5t2)e t(gb95f)ext(ze6f5)e h(bs3e2)ere (avFe3)so(gEC3e)me (aFE98)tex(8FZq2)t h(dq9aA)ere(cZ3cC)

function String() {
    var str =  "Some texte here some text here".replace(/(.{3})/g, "$1$");
    var mystring = str;
    var find = "$";
    var regex = new RegExp(find, "g");
    var fun = randomString();
    alert(mystring.replace(regex, fun));
    document.write(str);

    function randomString() {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        var string_length = 5;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }
        document.randform.randomfield.value = " ( " + randomstring + " ) ";
    }
}

2 个答案:

答案 0 :(得分:0)

首先,你的函数randomString()不会返回任何内容,所以有趣的事情总是一无所获。其次,你的发现正则表达式不起作用。

尝试使用这两个:

var find = '\\$+';

function randomString() {
   var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
   var string_length = 5;
   var randomstring = '';

   for (var i=0; i<string_length; i++) {
       var rnum = Math.floor(Math.random() * chars.length);
       randomstring += chars.substring(rnum,rnum+1);
   }

   return randomstring;
}

答案 1 :(得分:0)

我已对您的代码进行了一些修改,现在应该可以使用。

function String() {
var str =  "Some texte here some text here".replace(/(.{3})/g, function (x) 
{
return x + randomString();
});

document.write(str);

function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum,rnum+1);
}
return " ( " + randomstring + " ) ";
}
}