如何在javascript中替换字符串中的随机字符

时间:2013-03-23 22:03:03

标签: javascript algorithm

我想替换从另一个字符串中随机挑选的字符...

var charToTakeFrom = '0x080,0x081,0x082,0x083,0x084,0x085,0x086,0x087,0x088,0x089,0x090';
var givenString = 'The brown fox jumps over the pink fence.';

结果字符串应该用charToTakeFrom字符串中的随机字符替换givenString中的随机字符。

最简单的方法是编写 for 循环,用charToTakeFrom中的随机字符替换givenString中的随机字符数。

是否有更简单/更快的方法?

3 个答案:

答案 0 :(得分:1)

整言: Example

var ctu = [],s = "The bird flew majestically across the valley in search of worms.", newstring=" ";
ctu[0]="derp4561";
ctu[1]="derp12534";
ctu[2]="derp684";
var s = s.split(" ");
for(var i = 0;i<s.length;i++){      
s[i]=ctu[Math.floor(Math.random() * ctu.length)];
newstring +=s[i] + " ";
}
document.write(newstring);

单个字符: Example

var ctu = [],s = "The bird flew majestically across the valley in search of worms.", newstring="";
ctu[0]="0x080";
ctu[1]="0x081";
ctu[2]="0x082";
ctu[3]="0x083";
ctu[4]="0x084";
ctu[5]="0x085";
var s = s.split("");
for(var i = 0;i<s.length;i++){
if(s[i] != " "){
    s[i]=ctu[Math.floor(Math.random() * ctu.length)];
    newstring +=s[i];
}
else{
    newstring += " ";
}
}
document.write(newstring);

答案 1 :(得分:0)

我不确定这是否是最快的方式,但无论如何它足够怪癖=)希望你喜欢它

EDIT2 在JS上完成!

var complexity = 0.3; // 0 to .99 if more then more letters in src string will be replaced by random ones 
var randsArr = ("!@#$)**($#*)($#$()$()#$%^&*()%^$#$$#$^").split('').sort(function () { return 0.5 - Math.random()});
var srcArr = ("The brown fox jumps over the pink fence.").split('');
result = $.map(srcArr,function (el) { return (Math.random()>complexity) ? el : (randsArr.length) ? randsArr.shift() : el ; }).join('');
JSFiddle上的

Test it

旧的PHP版本,以防有人需要它:

$rands = "!@#$%^&*()";
$srcStr = "The brown fox jumps over the pink fence.";
$srcArr = str_split ($srcStr);
$randsArr = array_merge(str_split($rands),array_fill(strlen($rands),strlen($srcStr)-strlen($rands),false));
shuffle($randsArr);
echo implode(array_map(function($letter,$replacement) {  return ($replacement!=false)?$replacement:$letter;  },$srcArr,$randsArr));

编辑我的不好......我在想它是关于php =(给我几分钟时间在JS上重写它

答案 2 :(得分:0)

首先,您最好使用数组。然后:

var charToTakeFrom = [0x080,0x081,0x082,0x083,0x084,0x085,0x086,0x087,0x088,0x089,0x090];
var givenString = 'The brown fox jumps over the pink fence.';
var randomNumber = Math.floor((Math.random() * 10)) + 1); //Computes a random number from 1 to 11
var slicer = randomNumber - 1;
var slice = charToTakeFrom.slice(slicer, randomNumber); //get the character

我假设您已经知道如何替换字符串。