使用JavaScript计算字符串中的单词,不使用正则表达式

时间:2016-11-02 16:46:30

标签: javascript

关于如何计算JavaScript中字符串中单词数量的主题,有很多帖子,我只想说清楚我已经看过这些。

  

Counting words in string

     

Count number of words in string using JavaScript

作为一个非常新的程序员,我想在不使用任何正则表达式的情况下执行此功能。我对正则表达式一无所知,所以我想使用常规代码,即使它不是现实世界中最有效的方法,也是为了学习。

我在其他地方找不到任何问题的答案,所以我想在默认只使用正则表达式之前我会问这里。

    function countWords(str) {
      return str.split(/\s+/).length;
    }

我的总体目标是找到字符串中最短的单词。

2 个答案:

答案 0 :(得分:1)

似乎问题已经发生了一些变化,但是帖子中的第一个链接已经关闭了。修改为忽略双重空格:

function WordCount(str) {
   return str
     .split(' ')
     .filter(function(n) { return n != '' })
     .length;
}

console.log(WordCount("hello      world")); // returns 2

没有正则表达式 - 只需将字符串分解为空格中的数组,删除空项(双空格)并计算数组中的项数。

答案 1 :(得分:0)

所以,这是你的新问题的答案:

My overall goal is to find the shortest word in the string.

它像以前一样拆分字符串,从短到长的单词对数组进行排序,并返回第一个条目/最短的单词:

function WordCount(str) { 
    var words = str.split(" ");

    var sortedWords = words.sort(function(a,b) {
        if(a.length<b.length) return -1;
        else if(a.length>b.length) return 1;
        else return 0;
    });
   return sortedWords[0];
}

console.log(WordCount("hello to the world"));