【问题标题】:How to append some special character to a string in random position?如何将一些特殊字符附加到随机位置的字符串?
【发布时间】:2014-11-06 06:12:05
【问题描述】:

我试过了

function makeid()
{
    var chars = "!~/-^";
    var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
    var string_length = 8;
    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;
}
var output = makeid();
console.log(output);

使用上面的代码生成随机字符串现在我将如何将随机生成的字符串附加到给定字符串的随机位置。

谢谢

【问题讨论】:

  • 追加表示在最后,你要在中间拼接吗?
  • @dandavis 我想将生成的随机字符串添加到给定字符串的不同位置。

标签: javascript jquery random


【解决方案1】:

这对你有什么作用?

function makeid()
{
    var chars = "!~/-^";
    var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
    var string_length = 8; // did not use this.
    var randomstring = '';
    var randomNumber = Math.floor(Math.random()*st.length + 1);
    randomstring = st.substr(0, randomNumber) + chars + st.substr(randomNumber);
    return randomstring;
}
var output = makeid();
console.log(output);

这是另一种方式:

function makeid2()
{
    var chars = "!~/-^";
    var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
    var randomNumber = Math.floor(Math.random()*st.length + 1);
    var a = st.split("");
        a.splice(randomNumber,0,chars);
        return a.join("");

}
var output2 = makeid2();
console.log(output2);

【讨论】:

    【解决方案2】:

    使用数组对元素进行随机排序。

    $(function(){
    
    
    var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
    
    
    var array = st.split(" "),
        $ele = $("#result");
    
    
    for( var i=0; i<8; i++){
                       
       array = array.sort(function(){  return Math.random() -0.5 });
      
       $ele.val(  $ele.val() + "\n" + i + ": " + array.join(" ")  );
    }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea id='result' style="width:100%" rows="20"></textarea>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-24
      • 2021-01-19
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多