122

我试图以这种方式计算文本中的单词:

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"));
4

31 回答 31

132

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

str[i] === " "

或者charAt

str.charAt(i) === " "

你也可以这样做.split()

return str.split(' ').length;
于 2013-09-08T01:38:46.297 回答
122

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

使用 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- 这计算了空间。该脚本会在计数之前尝试删除所有多余的空格(双空格等)。如果文本包含两个单词之间没有空格,则将它们计为一个单词,例如“First sentence .Start of next sentence”。

于 2013-09-08T01:54:14.657 回答
26

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

function countWords(str) {
  var matches = str.match(/[\w\d\’\'-]+/gi);
  return matches ? matches.length : 0;
}
于 2014-01-15T17:41:20.297 回答
21

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

这里有两个简单的正则表达式来捕获字符串中的单词:

  • 非空白字符序列:/\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>

于 2015-05-19T20:51:19.007 回答
16

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

var getWordCount = function(v){
    var matches = v.match(/\S+/g) ;
    return matches?matches.length:0;
}
于 2013-09-08T01:46:40.497 回答
9

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

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

var str = 'one two three four five';

str.match(/\w+/g).length;
于 2016-08-24T13:54:11.607 回答
6

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

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

于 2016-03-31T14:33:58.817 回答
6

这将处理所有情况并尽可能高效。(除非您事先知道没有长度大于 1 的空格,否则您不想要 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 = '') {
  return text.split(/\S+/).length - 1;
};

console.log(wordCount(quote));//59
console.log(wordCount('f'));//1
console.log(wordCount('  f '));//1
console.log(wordCount('   '));//0
于 2019-11-16T23:51:04.130 回答
5

@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; 
}
于 2017-02-27T07:27:38.630 回答
4
function countWords(str) {
    var regEx = /([^\u0000-\u007F]|\w)+/g;  
    return str.match(regEx).length;
}

解释:

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

+匹配先前指定的单词字符的整个字符串 - 所以我们基本上对单词字符进行分组。

/g意味着它一直在寻找到最后。

str.match(regEx)返回找到的单词的数组 - 所以我们计算它的长度。

于 2017-11-21T09:59:41.833 回答
4

想要使用 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>

于 2018-11-07T08:39:33.933 回答
4

这是我的方法,它只是用空格分割一个字符串,然后 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,是正确的!

于 2019-03-12T02:49:22.367 回答
3

可能有一种更有效的方法来做到这一点,但这对我有用。

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 个单词)它也:

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

  • 将一个字母后跟一个新行计为一个单词-我发现此页面上给出的一些建议不计在内,例如:
    a
    a
    a
    a
    a
    有时被计为 0 x 个单词,并且其他功能仅将其计为 1 x 单词,而不是 5 x 单词)

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

于 2017-04-17T20:41:11.940 回答
3
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length
于 2017-12-08T09:12:46.773 回答
3

准确性也很重要。

选项 3 所做的基本上是用 a 替换除任何空格以外的所有空格,+1然后对其进行评估以计算1',从而为您提供字数。

这是我在这里做过的四种方法中最准确和最快的。

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

请参阅下面的文件 ops/s 和返回的字数。

这是运行此基准测试的链接。 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.

于 2019-11-10T14:42:03.667 回答
2

这是一个计算 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
于 2017-05-19T09:13:40.823 回答
2

我不确定这是否之前已经说过,或者它是否是这里需要的,但是你不能把字符串变成一个数组然后找到长度吗?

let randomString = "Random String";

let stringWords = randomString.split(' ');
console.log(stringWords.length);
于 2018-08-09T14:02:32.413 回答
2
function countWords(str) {
    str = str.replace(/(^\s*)|(\s*$)/gi,"");
    str = str.replace(/[ ]{2,}/gi," ");
    str = str.replace(/\n /,"\n");
    return str.split(' ').length;
}
document.write(countWords("  this function remove extra space and count the real   string lenth"));
于 2021-06-29T19:58:11.673 回答
1

你的代码中有一些错误。

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”。它不计算不包含字母或数字的单词。

于 2015-06-26T14:37:05.583 回答
1

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

function countWords(str) {
    var matches = str.match(/\S+/g);
    return matches ? matches.length : 0;
}
于 2016-03-14T11:09:57.253 回答
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

我希望这可以帮助那些正在寻找这三个答案的人。

于 2019-02-28T08:23:36.940 回答
1

如果你想计算特定的单词

function countWholeWords(text, keyword) {
    const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));

    if (times) {
        console.log(`${keyword} occurs ${times.length} times`);
    } else {
        console.log(keyword + " does not occurs")
    }
}


const text = `
In a professional context it often happens that private or corporate clients corder a publication to be 
made and presented with the actual content still not being ready. Think of a news blog that's 
filled with content hourly on the day of going live. However, reviewers tend to be distracted 
by comprehensible content, say, a random text copied from a newspaper or the internet.
`

const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]

wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));


// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times
于 2021-01-10T15:14:57.913 回答
1

您可以使用此算法:

应用程序.js:

const TextArea = document.querySelector('textarea');

const CountContainer = document.querySelector('#demo');


TextArea.addEventListener('keypress', () => {
    let TextValue = TextArea.value.split(' ').join('-').split('\n').join('-').split('-');

    let WordCountArray = TextValue.filter(el => {
        return el != '';
    });

    let WordSen = WordCountArray.length <= 1 ? 'Word' : 'Words';

    console.log(WordCountArray);

    CountContainer.textContent = WordCountArray.length + ' ' + WordSen;

});

TextArea.addEventListener('keyup', function () {
    if (this.value === '') CountContainer.textContent = '0 Word';
});

用于测试的 HTML 索引页:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <textarea cols="30" rows="10"></textarea>
    <div id="demo"></div>

    <script src="app.js"></script>
</body>


</html>

于 2021-03-19T20:59:28.497 回答
1

改编自 internals-in answer 它也处理边缘情况“”

export const countWords = (str: string) => {

  str = str.trim();
  if (!str.length) {
    return str.length
  }
  return str.trim().split(/\s+/).length;
}

开玩笑测试

    test("countwords", () => {
        expect(countWords('  ')).toBe(0)
        expect(countWords('78   7 ')).toBe(2)
        expect(countWords('78 7 ')).toBe(2)
        expect(countWords('aa, , 7')).toBe(3)
        expect(countWords('aa, , \n \n \t 7 \n 4')).toBe(4)
    }); 
于 2021-04-08T12:02:19.937 回答
1

此代码段将计算句子中有多少单词:

let para = "hello world I am javascript";
console.log(para.split(" ").filter((x) => x !== "").length)

于 2021-09-13T09:05:47.903 回答
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>
于 2014-01-09T10:14:28.083 回答
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());
于 2018-03-16T10:43:26.683 回答
0
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));
于 2019-11-20T10:08:46.390 回答
0
var str =   "Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore illum fuga magni exercitationem porro? Eaque tenetur tempora nesciunt laborum deleniti, quidem nemo consequuntur voluptate alias ad soluta, molestiae, voluptas libero!" ;

let count = (str.match(/\s/g) || []).length;
console.log(count + 1 );

countWords =(str )=>{

    let count =  ( str.match(/\s/g)   || []  ).length;
    count = (count == 0 ) ? 0 : count +1  ; 
    return count 
}
于 2021-05-09T19:34:50.057 回答
0

您可以使用这种简单的方法:

function wordCounter(text) {
  let arr = text.split('');
  return arr.length;
}
于 2022-01-06T01:22:24.533 回答
0

这非常简单,即使单词之间有多个空格,也能准确计算单词:

return string.split(/\s+/).length;

正则表达式解释

部分表达 解释
\s 匹配任何空白字符
+ 匹配前一个令牌一次到无限次
于 2022-01-12T00:46:28.917 回答