代码之家  ›  专栏  ›  技术社区  ›  user1627930

javascript用下划线替换随机字母

  •  -1
  • user1627930  · 技术社区  · 7 年前

    我想写这个谷歌电子表格javascript代码来替换字符串中的随机字母。

    我已经创建了一个代码,它可以执行但不能随机执行,而且它还用下划线替换了空格(这是有问题的)。

    我感兴趣的最终结果是从这里开始(句子是法语btw.):

    'J’habite à New York.'

    为此:

    '_’h_b_t_ à _ew _or_.'

    假设给定一个句子,至少一半的字母必须用下划线替换。

    谢谢你的帮助。(附:我不是程序员)

    到目前为止,我掌握的代码是:

    var v =  [['J’habite à New York.', 'Sì', ], ['Je m’appelle John. !']]; 
    
    for (var r in v){
      for (var c in v[r]){
        var d = v[r][c];
        var l = d.length; 
    
        var u = l; 
        while(u > 0){
        var res = d.replace(d[u-2], '_');
        d = res; 
        u = u - 2;
          }
        console.log(res);
          }
        }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Murys    7 年前

    var a = "Text i want to replace text from";
    var splitted = a.split('');
    var count = 0; // variable where i keep trace of how many _ i have inserted
    
    while(count < a.length/2) {
       var index = Math.floor(Math.random()*a.length); //generate new index
       if(splitted[index] !== '_' && splitted[index] !== ' ') {
           splitted[index] = '_';
           count++;
       } 
    }
    
    var newstring = splitted.join(""); //the new string with spaces replaced
    

    splitted[index] = ' _ ';
    

    splitted[index] = '_';
    

    if(splitted[index] !== '_')
    

    if(splitted[index] !== '_' && splitted[index] !== ' ')
    

        2
  •  2
  •   Luca Kiebel    7 年前

    function replace(str) {
      return str.split("").map(char => Math.random() > 0.5 ? "_" : char).join("");
    }
    
    
    var v = [
      ['J’habite à New York.', 'Sì', ],
      ['Je m’appelle John. !', 'Non!',]
    ];
    
    
    for (const pair of v) {
      pair[0] = replace(pair[0]);
      pair[1] = replace(pair[1]);
    }
    
    console.log(v)