从字符串中随机输出字母

时间:2015-04-26 15:22:17

标签: javascript jquery arrays substr

我想从字符串中删除3个RANDOM字母。

我可以使用类似substr()slice()的功能,但它不会让我随机输出字母。

这是我现在所拥有的演示。

http://jsfiddle.net/euuhyfr4/

任何帮助将不胜感激!

6 个答案:

答案 0 :(得分:3)

var str = "hello world";
for(var i = 0; i < 3; i++) {
    str = removeRandomLetter(str);
}
alert(str);

function removeRandomLetter(str) {
    var pos = Math.floor(Math.random()*str.length);
    return str.substring(0, pos)+str.substring(pos+1);
}

如果你想用其他随机字符替换3个随机字符,你可以使用3次这个函数:

function substitute(str) { 
    var pos = Math.floor(Math.random()*str.length); 
    return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1); 
} 
function getRandomLetter() { 
    var  letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 
    var pos = Math.floor(Math.random()*letters.length); 
    return letters.charAt(pos); 
}

答案 1 :(得分:1)

您可以split将字符串添加到数组,splice随机项,然后join返回字符串:

var arr = str.split('');
for(var i=0; i<3; ++i)
    arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');

答案 2 :(得分:1)

var str = "cat123",
    amountLetters = 3,
    randomString = "";

for(var i=0; i < amountLetters; i++) {
  randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);

小提琴: http://jsfiddle.net/euuhyfr4/7/

答案 3 :(得分:1)

This answer表示

  

将字符串切片两次比使用分割后跟连接[...]

更快

因此,虽然Oriol's answer完美无缺,但我相信更快的实施方式是:

function removeRandom(str, amount)
{
    for(var i = 0; i < amount; i++)
    {
        var max = str.length - 1;
        var pos = Math.round(Math.random() * max);
        str = str.slice(0, pos) + str.slice(pos + 1);
    }
    return str;
}

另见this fiddle

答案 4 :(得分:1)

你可以在字符串中随机播放字符,然后删除前3个字符

var str = 'congratulations';

String.prototype.removeItems = function (num) {
    var a = this.split(""),
        n = a.length;

    for(var i = n - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    return a.join("").substring(num);
}

alert(str.removeItems(3));

答案 5 :(得分:-1)

您可以使用不带任何参数的split方法。 这会将所有字符作为数组返回。

然后您可以使用Generating random whole numbers in JavaScript in a specific range?中所述的任何随机函数,然后使用该位置获取该位置的角色。

看看我在这里的实施

var str = "cat123";
var strArray = str.split("");

function getRandomizer(bottom, top) {
        return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
    }
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);

alert("Character @ random position " + strArray[nrand]);

Code @ here https://jsfiddle.net/1ryjedq6/

相关问题