来自文本JavaScript / Ajax的随机单词

时间:2014-06-06 06:59:23

标签: javascript ajax random

我需要从文本中获取1个随机单词,但我现在不知道如何使用Javascript。

代码:

function someFunction() {

    // something here

var word;

$.ajax({
     async: false,
     type: 'GET',
     url: link,
     success: function(data) {
        word = getWord(data); // get random word from data
     }
});

}



function getWord(text) {

// help me please)

}

我希望这很简单)谢谢大家!

2 个答案:

答案 0 :(得分:1)

像这样的东西

function getWord(text) {
    var words = text.split(' ');
    return words[getRandomInt(0, words.length-1)];
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

答案 1 :(得分:1)

尝试类似http://jsfiddle.net/Y9bCG/

的内容
alert(getWord("there is a book there"));
function getWord(data)
{   
    var splits=data.split(' ');    

    var randNumMax = splits.length-1;
    var randInt = (Math.floor(Math.random() * (randNumMax + 1)));
    return splits[randInt];
}