计算字符串中的单词


91

我试图以此方式对文本中的单词进行计数:

function WordCount(str) {
  var totalSoFar = 0;
  for (var i = 0; i < WordCount.length; i++)
    if (str(i) === " ") { // if a space is found in str
      totalSoFar = +1; // add 1 to total so far
  }
  totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}

console.log(WordCount("Random String"));

我认为我已经很好地理解了这一点,除了我认为if陈述是错误的。检查是否str(i)包含空格的部分并加1。

编辑:

我发现(感谢Blender)可以用更少的代码来做到这一点:

function WordCount(str) { 
  return str.split(" ").length;
}

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

会不会str.split(' ').length是更简单的方法?jsfiddle.net/j08691/zUuzd
j08691 2013年

还是str.split(' ')然后计算不是长度为0的字符串?
凯蒂·基利安

8
string.split('').length不起作用。空格并不总是单词边界!如果两个单词之间有多个空格怎么办?关于什么 ”。 。 。” ?
阿洛索2015年

正如Aloso所说,这种方法行不通。
现实-洪流

1
@ Reality-Torrent这是旧帖子。
cst1992 '16

Answers:


107

使用方括号,而不是括号:

str[i] === " "

charAt

str.charAt(i) === " "

您也可以使用.split()

return str.split(' ').length;

我想我明白您的意思,上面编辑的原始问题中的我的代码看起来还好吗?

您的解决方案在用空格字符以外的其他字符分隔单词的地方有效吗?用换行符或制表符说?
nemesisfixx

7
@Blender很好的解决方案,但是对于字符串中省略的双
精度

95

在重新发明轮子之前尝试这些

使用JavaScript计算字符串中的单词数

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

来自http://www.mediacollege.com/internet/javascript/text/count-words.html

function countWords(s){
    s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
    s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
    s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
    return s.split(' ').filter(function(str){return str!="";}).length;
    //return s.split(' ').filter(String).length; - this can also be used
}

使用JavaScript计算字符串中的单词开始,而无需使用正则表达式 -这将是最好的方法

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

作者注:

您可以修改此脚本以使用任意方式对单词进行计数。重要的部分是s.split(' ').length-这要计算空间。该脚本尝试在计数之前删除所有多余的空格(双精度空格等)。如果文本包含两个单词,并且两个单词之间没有空格,则将它们视为一个单词,例如“第一句。下一个句子的开始”。


我从未见过这种语法:s = s.replace(/(^ \ s *)|(\ s * $)/ gi,“”); s = s.replace(/ [] {2,} / gi,“”); s = s.replace(/ \ n /,“ \ n”); 每行是什么意思?很抱歉这么需要

有什么事吗 此代码非常混乱,从字面上复制并粘贴的网站根本没有帮助。我只是比我得到的东西更困惑,它应该检查没有空格的单词我们的双倍空格,但是如何?只是一百万个随机放置的字符确实无济于事

很好,我只是想让您解释您编写的代码。我以前从未看过语法,想知道它的含义。好的,我提出了一个单独的问题,有人深入回答了我的问题。对不起,要求这么多。

1
str.split(/ \ s + /)。length并不是按原样工作的:尾随空格被视为另一个单词。
伊恩

2
请注意,对于空输入,它返回1。
pie6k '17

21

计算字符串中单词的另一种方法。此代码计算仅包含字母数字字符和“ _”,“'”,“-”,“'”字符的单词。

function countWords(str) {
  var matches = str.match(/[\w\d\’\'-]+/gi);
  return matches ? matches.length : 0;
}

2
可能还会考虑添加,’'-这样“猫的喵”就不会算作3个字。和“之间”
mpen

@mpen感谢您的建议。我已经根据它更新了答案。
亚历克斯(Alex)

我字符串中的第一个字符是用引号引起来的FYI,而不是反引号:-D
mpen,

1
您不需要’'在正则表达式中转义。使用/[\w\d’'-]+/gi以避免ESLint没有无用逃逸警告
斯特凡Blamberg

18

清理字符串后,可以匹配非空白字符或单词边界。

这是两个简单的正则表达式,用于捕获字符串中的单词:

  • 非空白字符序列: /\S+/g
  • 单词边界之间的有效字符: /\b[a-z\d]+\b/g

下面的示例演示如何使用这些捕获模式从字符串中检索字数统计。

/*Redirect console output to HTML.*/document.body.innerHTML='';console.log=function(s){document.body.innerHTML+=s+'\n';};
/*String format.*/String.format||(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return"undefined"!=typeof a[n]?a[n]:m})}([].slice.call(arguments,1))});

// ^ IGNORE CODE ABOVE ^
//   =================

// Clean and match sub-strings in a string.
function extractSubstr(str, regexp) {
    return str.replace(/[^\w\s]|_/g, '')
        .replace(/\s+/g, ' ')
        .toLowerCase().match(regexp) || [];
}

// Find words by searching for sequences of non-whitespace characters.
function getWordsByNonWhiteSpace(str) {
    return extractSubstr(str, /\S+/g);
}

// Find words by searching for valid characters between word-boundaries.
function getWordsByWordBoundaries(str) {
    return extractSubstr(str, /\b[a-z\d]+\b/g);
}

// Example of usage.
var edisonQuote = "I have not failed. I've just found 10,000 ways that won't work.";
var words1 = getWordsByNonWhiteSpace(edisonQuote);
var words2 = getWordsByWordBoundaries(edisonQuote);

console.log(String.format('"{0}" - Thomas Edison\n\nWord count via:\n', edisonQuote));
console.log(String.format(' - non-white-space: ({0}) [{1}]', words1.length, words1.join(', ')));
console.log(String.format(' - word-boundaries: ({0}) [{1}]', words2.length, words2.join(', ')));
body { font-family: monospace; white-space: pre; font-size: 11px; }


寻找独特的单词

您还可以创建单词映射以获得唯一计数。

function cleanString(str) {
    return str.replace(/[^\w\s]|_/g, '')
        .replace(/\s+/g, ' ')
        .toLowerCase();
}

function extractSubstr(str, regexp) {
    return cleanString(str).match(regexp) || [];
}

function getWordsByNonWhiteSpace(str) {
    return extractSubstr(str, /\S+/g);
}

function getWordsByWordBoundaries(str) {
    return extractSubstr(str, /\b[a-z\d]+\b/g);
}

function wordMap(str) {
    return getWordsByWordBoundaries(str).reduce(function(map, word) {
        map[word] = (map[word] || 0) + 1;
        return map;
    }, {});
}

function mapToTuples(map) {
    return Object.keys(map).map(function(key) {
        return [ key, map[key] ];
    });
}

function mapToSortedTuples(map, sortFn, sortOrder) {
    return mapToTuples(map).sort(function(a, b) {
        return sortFn.call(undefined, a, b, sortOrder);
    });
}

function countWords(str) {
    return getWordsByWordBoundaries(str).length;
}

function wordFrequency(str) {
    return mapToSortedTuples(wordMap(str), function(a, b, order) {
        if (b[1] > a[1]) {
            return order[1] * -1;
        } else if (a[1] > b[1]) {
            return order[1] * 1;
        } else {
            return order[0] * (a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0));
        }
    }, [1, -1]);
}

function printTuples(tuples) {
    return tuples.map(function(tuple) {
        return padStr(tuple[0], ' ', 12, 1) + ' -> ' + tuple[1];
    }).join('\n');
}

function padStr(str, ch, width, dir) { 
    return (width <= str.length ? str : padStr(dir < 0 ? ch + str : str + ch, ch, width, dir)).substr(0, width);
}

function toTable(data, headers) {
    return $('<table>').append($('<thead>').append($('<tr>').append(headers.map(function(header) {
        return $('<th>').html(header);
    })))).append($('<tbody>').append(data.map(function(row) {
        return $('<tr>').append(row.map(function(cell) {
            return $('<td>').html(cell);
        }));
    })));
}

function addRowsBefore(table, data) {
    table.find('tbody').prepend(data.map(function(row) {
        return $('<tr>').append(row.map(function(cell) {
            return $('<td>').html(cell);
        }));
    }));
    return table;
}

$(function() {
    $('#countWordsBtn').on('click', function(e) {
        var str = $('#wordsTxtAra').val();
        var wordFreq = wordFrequency(str);
        var wordCount = countWords(str);
        var uniqueWords = wordFreq.length;
        var summaryData = [
            [ 'TOTAL', wordCount ],
            [ 'UNIQUE', uniqueWords ]
        ];
        var table = toTable(wordFreq, ['Word', 'Frequency']);
        addRowsBefore(table, summaryData);
        $('#wordFreq').html(table);
    });
});
table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 200px;
    font-family: monospace;
}
thead {
    border-bottom: #000 3px double;;
}
table, td, th {
    border: #000 1px solid;
}
td, th {
    padding: 2px;
    width: 100px;
    overflow: hidden;
}

textarea, input[type="button"], table {
    margin: 4px;
    padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1>Word Frequency</h1>
<textarea id="wordsTxtAra" cols="60" rows="8">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.</textarea><br />
<input type="button" id="countWordsBtn" value="Count Words" />
<div id="wordFreq"></div>


1
这是一个很棒的综合答案。感谢所有示例,它们非常有用!
康纳

14

我认为这种方法比您想要的更多

var getWordCount = function(v){
    var matches = v.match(/\S+/g) ;
    return matches?matches.length:0;
}

7

String.prototype.match 返回一个数组,然后我们可以检查长度,

我发现这种方法最具描述性

var str = 'one two three four five';

str.match(/\w+/g).length;

1
如果字符串为空,则可能发生错误
Purkhalo Alex

5

到目前为止,我找到的最简单的方法是使用带有split的正则表达式。

var calculate = function() {
  var string = document.getElementById('input').value;
  var length = string.split(/[^\s]+/).length - 1;
  document.getElementById('count').innerHTML = length;
};
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculate()">Calculate</button>
<span id="count">7</span> words


3

@ 7-isnotbad给出的答案非常接近,但是不算单字行。这是解决方法,它似乎可以解决单词,空格和换行符的所有可能组合。

function countWords(s){
    s = s.replace(/\n/g,' '); // newlines to space
    s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
    return s.split(' ').length; 
}

3

这是我的方法,它简单地用空格分隔字符串,然后for循环数组,如果array [i]与给定的正则表达式模式匹配,则增加计数。

    function wordCount(str) {
        var stringArray = str.split(' ');
        var count = 0;
        for (var i = 0; i < stringArray.length; i++) {
            var word = stringArray[i];
            if (/[A-Za-z]/.test(word)) {
                count++
            }
        }
        return count
    }

像这样调用:

var str = "testing strings here's a string --..  ? // ... random characters ,,, end of string";
wordCount(str)

(添加了额外的字符和空格以显示功能的准确性)

上面的str返回10,这是正确的!


一些语言不使用[A-Za-z]在所有
大卫

2

可能有一种更有效的方法来执行此操作,但这对我有用。

function countWords(passedString){
  passedString = passedString.replace(/(^\s*)|(\s*$)/gi, '');
  passedString = passedString.replace(/\s\s+/g, ' '); 
  passedString = passedString.replace(/,/g, ' ');  
  passedString = passedString.replace(/;/g, ' ');
  passedString = passedString.replace(/\//g, ' ');  
  passedString = passedString.replace(/\\/g, ' ');  
  passedString = passedString.replace(/{/g, ' ');
  passedString = passedString.replace(/}/g, ' ');
  passedString = passedString.replace(/\n/g, ' ');  
  passedString = passedString.replace(/\./g, ' '); 
  passedString = passedString.replace(/[\{\}]/g, ' ');
  passedString = passedString.replace(/[\(\)]/g, ' ');
  passedString = passedString.replace(/[[\]]/g, ' ');
  passedString = passedString.replace(/[ ]{2,}/gi, ' ');
  var countWordsBySpaces = passedString.split(' ').length; 
  return countWordsBySpaces;

}

它能够将以下所有内容识别为单独的单词:

abc,abc= 2个单词,
abc/abc/abc= 3个单词(可使用正斜杠和反斜杠),
abc.abc= 2个单词,
abc[abc]abc= 3个单词,
abc;abc= 2个单词,

(我尝试过的其他一些建议也将上面的每个示例算为1个x字),它也:

  • 忽略所有前导和尾随空格

  • 计数单字母后跟一个新行,因为一个字-我已经发现了一些在此页面上给出的建议不计,例如:
    一个
    一个
    一个
    一个
    一个
    有时被算作0 X字,其他功能仅将其计为1 x字,而不是5 x字)

如果有人对如何改进它,或者更清洁/更高效有任何想法,请加2美分!希望这可以帮助到别人。


2
function countWords(str) {
    var regEx = /([^\u0000-\u007F]|\w)+/g;  
    return str.match(regEx).length;
}

说明:

/([^\u0000-\u007F]|\w)匹配单词字符-很棒-> regex为我们完成了繁重的工作。(此模式基于以下SO答案:https : //stackoverflow.com/a/35743562/1806956 @Landeeyo的)

+ 匹配先前指定的单词字符的整个字符串-因此我们基本上将单词字符分组。

/g 表示它一直在寻找直到最后。

str.match(regEx) 返回找到的单词的数组-因此我们计算其长度。


1
复杂的正则表达式是巫术的艺术。我们学会了发音的咒语,但从来没有胆量问为什么。感谢你的分享。
布莱斯

^那是一个了不起的报价
r3wt '18

我收到此错误:错误正则表达式中的意外控制字符:\ x00 no-control-regex
Aliton Oliveira

如果字符串以/或(
Walter Monecke

@WalterMonecke刚刚在chrome上进行了测试-没有收到错误。您在哪里出错了?谢谢
Ronen Rabinovici

2

对于那些想要使用Lodash的人可以使用以下_.words功能:

var str = "Random String";
var wordCount = _.size(_.words(str));
console.log(wordCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


2

这将处理所有情况,并尽可能有效。(除非您事先知道不存在长度大于一个的空格,否则您不要split('')。):

var quote = `Of all the talents bestowed upon men, 
              none is so precious as the gift of oratory. 
              He who enjoys it wields a power more durable than that of a great king. 
              He is an independent force in the world. 
              Abandoned by his party, betrayed by his friends, stripped of his offices, 
              whoever can command this power is still formidable.`;

function WordCount(text) {
    text = text.trim();
    return text.length > 0 ? text.split(/\s+/).length : 0;
}
console.log(WordCount(quote));//59
console.log(WordCount('f'));//1
console.log(WordCount('  f '));//1
console.log(WordCount('   '));//0

1

这是一个计算HTML代码中单词数的函数:

$(this).val()
    .replace(/((&nbsp;)|(<[^>]*>))+/g, '') // remove html spaces and tags
    .replace(/\s+/g, ' ') // merge multiple spaces into one
    .trim() // trim ending and beginning spaces (yes, this is needed)
    .match(/\s/g) // find all spaces by regex
    .length // get amount of matches

1
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length

6
尽管此代码段可以解决问题,但提供说明确实有助于提高您的帖子质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您提出代码建议的原因。
伊斯玛(Isma)

1

我不确定这是以前说过的,还是这里需要的内容,但是您不能将字符串设置为数组然后找到长度吗?

let randomString = "Random String";

let stringWords = randomString.split(' ');
console.log(stringWords.length);

1

我认为这个答案将为以下问题提供所有解决方案:

  1. 给定字符串中的字符数
  2. 给定字符串中的单词数
  3. 给定字符串中的行数

 function NumberOf() { 
		 var string = "Write a piece of code in any language of your choice that computes the total number of characters, words and lines in a given text. \n This is second line. \n This is third line.";

		 var length = string.length; //No of characters
		 var words = string.match(/\w+/g).length; //No of words
		 var lines = string.split(/\r\n|\r|\n/).length; // No of lines

		 console.log('Number of characters:',length);
		 console.log('Number of words:',words);
		 console.log('Number of lines:',lines);


}

NumberOf();

  1. 首先,您需要通过以下方式找到给定字符串的长度 string.length
  2. 然后,您可以通过将它们与字符串匹配来找到单词数 string.match(/\w+/g).length
  3. 最后,您可以像这样分割每一行 string.length(/\r\n|\r|\n/).length

希望这对正在寻找这三个答案的人有所帮助。


1
优秀。请将变量名更改为string其他名称。令人困惑。使我想了一秒钟的string.match()是静态方法。干杯。
Shy Agam

是的!当然。@ShyAgam
的LiN

1

准确性也很重要。

选项3所做的基本上是用a替换所有但所有的空格,+1然后对其求值以计算1从而为您提供单词计数。

这是我在这里完成的四种方法中最准确,最快的方法。

请注意,它比return str.split(" ").length;Microsoft Word慢,但准确。

请参阅下面的文件操作和返回的字数。

这是运行此基准测试的链接。 https://jsbench.me/ztk2t3q3w5/1

// This is the fastest at 111,037 ops/s ±2.86% fastest
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(" ").length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 2nd fastest at 46,835 ops/s ±1.76% 57.82% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(/(?!\W)\S+/).length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 3rd fastest at 37,121 ops/s ±1.18% 66.57% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/\S+/g,"\+1");
  return eval(str);
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.

// This is the slowest at 89 ops/s 17,270 ops/s ±2.29% 84.45% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/(?!\W)\S+/g,"1").replace(/\s*/g,"");
  return str.lastIndexOf("");
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.


1
function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 1; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar ++;
        }
    }
    return totalSoFar; 
}
console.log(WordCount("hi my name is raj));

2
该网站通常不提供纯代码答案。您能否编辑答案以包含一些注释或代码说明?解释应回答以下问题:它是做什么的?它是如何做到的?去哪儿了?它如何解决OP的问题?请参阅:如何anwser。谢谢!
Eduardo Baitello

0
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type="text/javascript">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>

0

我知道它晚了,但是这个正则表达式应该可以解决您的问题。这将匹配并返回字符串中的单词数。而不是您标记为解决方案的解决方案,即使它实际上只是1个单词,也将把space-space-word计为2个单词。

function countWords(str) {
    var matches = str.match(/\S+/g);
    return matches ? matches.length : 0;
}

0

您的代码中有一些错误。

function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar += 1;
        }
    }
    return totalSoFar + 1; // you need to return something.
}
console.log(WordCount("Random String"));

使用正则表达式还有另一种简单的方法:

(text.split(/\b/).length - 1) / 2

确切的值可以相差大约1个单词,但是它还会计算没有空格的单词边界,例如“ word-word.word”。而且它不计算不包含字母或数字的单词。


0
function totalWordCount() {
  var str ="My life is happy"
  var totalSoFar = 0;

  for (var i = 0; i < str.length; i++)
    if (str[i] === " ") { 
     totalSoFar = totalSoFar+1;
  }
  totalSoFar = totalSoFar+ 1; 
  return totalSoFar
}

console.log(totalWordCount());

请添加一些解释来编辑您的答案,避免仅使用代码答案
GGO
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.