将句子拆分成单词数组

时间:2015-06-28 22:36:00

标签: javascript

伙计们,我试图找出输入句子中word最长的内容,但代码没有输出任何内容。请问smb请帮帮我吗?

<!DOCTYPE html>
<html>
<head lang = "en">
    <meta charset = "UTF-8">
    <title>LongestWord</title>
</head>
<body>
<script language = "Javascript" type = "text/javascript">
    var sentence = prompt("Enter sentence: ");
    var splitted = sentence.split("\\s+");
    var longestWord = splitted[0];

    for(var i = 0; i < splitted.length; i++){
        for(var j = 0; j < splitted[i].length - 1; j++){
            if(longestWord.length < splitted[i].length){
                longestWord = splitted[i];
            }

        }
    }
    document.write("The longest word in the sentence is " + longestWord);  
</script>
</body>
</html>

4 个答案:

答案 0 :(得分:4)

将您的正则表达式代码更改为:

var splitted = sentence.split(/\s+/);

编辑:以下是对该功能略有不同的看法:

function longestWord(str) {
    return str.split(/\s+/).sort(function(w1, w2) {return w2.length - w1.length;})[0];    
}

var phrase = "dmitriy nesterkin drd";
console.log(longestWord(phrase));

答案 1 :(得分:0)

var length = 0;
var longestWord = "";
sentence.split(" ").forEach(function(word){
  if(word.length > length) {
    length = word.length;
    longestWord = word;
  }
});
document.write("The longest word in the sentence is " + longestWord);

答案 2 :(得分:0)

以下是使用splitreduce的简化版本。第一个被发现的词占上风。

var longestWord = sentence.split(' ').reduce(function(longestWord, word){
  return word.length > longestWord.length ? word : longestWord;
}, '');

答案 3 :(得分:0)

您可以轻松地为sort()函数创建比较函数。这样,您可以通过弹出生成的排序数组来检查是否有多个单词与最长单词的长度匹配。

function compare_words(a, b) { return a.length - b.length; }

var words = ["Hello", "here", "are", "some", "words", "of", "variable", "length"];

console.log("Longest word is: " + words.sort(compare_words).pop());