我的代码中有一个字符串。我想删除 80% 的字符串字母并将它们替换为“_”(下划线)。
我已经设法用“_”替换了所有的字符串字符,但我不能让它只替换我的字符串的 80%。
var a = "mystring";
var splitted = a.split('');
var count = 0;
while(count < a.length) {
if(splitted[count] !== '_' && splitted[count] !== ' ') {
splitted[count] = '_ ';
count++;
}
}
console.log(splitted);
代码输出:_ _ _ _ _ _ _ _
期望输出:_ y _ _ _ _ _ _
或者:_ _ _ _ _ _ _
或者:_ _ _ _ _ _ 我 _
最佳答案
如果你想重新放置 80% 的字符串,你需要搜索单词的所有长度然后乘以 0.8 然后执行 while 以重新放置一个随机字母。
var string = 'mystring';
var splitted = string.split('');
var percent = Math.round(splitted.length * 0.8);
var changues =0;
while (changues<percent){
var random = Math.floor((Math.random() * splitted.length ) + 0);
if(splitted[random]!='_'){
splitted[random]='_';
changues++;
}
}
string=splitted.join('');
console.log(string);
关于javascript - 如何在 JavaScript 中用 "underscore"( "_ ") 替换字符串的 80%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439582/