javascript - 如何在 JavaScript 中用 "underscore"( "_ ") 替换字符串的 80%?

标签 javascript arrays node.js string

我的代码中有一个字符串。我想删除 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/

相关文章:

javascript - 如何创建if语句来处理html中的空字符串

javascript - 只发送一次 Ajax 请求

javascript - 单击时获取 Canvas 元素的 ID

Python numpy 数组之间共享指针

node.js - 类型错误 : Cannot read property 'avatarURL' of null | Trying to export the help command

javascript - promise Stripe API

javascript - 不稳定的移动物体 Javascript

javascript - 使用 JQuery 删除动态创建的 Div 时出现问题

php - 选择多个将一个单词替换为数组中的每个值

javascript - 无法想到在 JIRA 中创建插件的起点