在字符串中计数单词

我试着用这种方法数课文中的单词:

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"));
314603 次浏览

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

str[i] === " "

charAt:

str.charAt(i) === " "

你也可以用 .split():

return str.split(' ').length;

我认为这个方法比你想要的要多

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

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

使用 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ーー这计算了 空间。 该脚本试图在计数之前删除所有额外的空格(双倍空格等)。 如果文本包含两个没有空格的单词,它将把它们视为一个单词,例如: 。开始下一句”。

<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>

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

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

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

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

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


Finding Unique Words

You could also create a mapping of words to get unique counts.

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>

你的代码有些错误。

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个单词,但它也计算没有空格的单词边界,例如“单词-单词”。单词”。它不计算不包含字母或数字的单词。

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

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

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

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

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

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

var str = 'one two three four five';


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

@ 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;
}

也许有一个更有效的方法来做到这一点,但这是什么为我工作。

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个单词,< br >

(一些其他的建议,我已经尝试计算每个例子以上只有1 x 字) 它还包括:

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

  • 一个单字母后跟一个新行作为一个单词——我发现这一页给出的一些建议不算数,例如:





    有时被计算为0 x 个单词,而其他函数只计算为1 x 个单词,而不是5 x 个单词) < br > < br >

如果任何人有任何关于如何改善它的想法,或更清洁/更有效-然后请增加你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
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)返回找到的单词的数组-所以我们计算它的长度。

let leng = yourString.split(' ').filter(a => a.trim().length > 0).length
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());

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

let randomString = "Random String";


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

对于那些想使用 Lodash 的用户,可以使用 ABc1功能:

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>

我认为这个答案将给出所有的解决方案:

  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. 最后你可以像这样拆分每一行

我希望这能帮助那些正在寻找这3个答案的人。

下面是我的方法,它简单地用空格分割字符串,然后 for 循环数组,如果数组[ 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,这是正确的!

准确性也很重要。

选项3所做的基本上就是用 +1替换所有的空格(除了任何空格) ,然后计算这个值来计算 1给出的单词计数。

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

请注意,它是慢于 return str.split(" ").length;,但它是准确的,当比较微软的 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.

这将处理所有的情况,并尽可能有效。(除非事先知道没有长度大于1的空格,否则不需要拆分(’)。):

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

如果你想数具体的单词

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

你可以使用这个算法:

App.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>


改编自内部-在回答 它处理的边缘情况下’

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

这个片段将计算句子中有多少个单词:

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

你可以用这个简单的方法:

function wordCounter(text) {
let arr = text.split('');
return arr.length;
}

这个一行程序非常简单,即使单词之间有不止一个空格,它也能准确地计算单词数量:

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

正则表达式解释

表达的一部分 解释
\s 符合任何空白字符
+ 在一次和无限次之间匹配以前的标记

标准 /s+/方法的问题在于它不处理带连字符的单词。我试图将它作为一个单独的正则表达式(/\s+|\w-\w/和一些变体)执行,但是失败了许多测试,特别是由于重叠匹配。最后,我决定采取以下措施:

function wordcount(s) {
return s.replace(/-/g, ' ').trim().split(/\s+/g).length;
}

它通过以下测试:

const test_sentences = [
{ sentence: "hello world.", word_count: 2 },
{ sentence: "hello world - how are you", word_count: 5 },
{ sentence: "hello 10 world - how are you?", word_count: 6 },
{ sentence: "   hello 10 world - how are you? 10   ", word_count: 7 },
{ sentence: "Test of-hyphens in a-string", word_count: 6 },
{ sentence: "Test of-hyphens -- in an-string ---", word_count: 6 },
{ sentence: "Test-of-hyphens -- in-a-string ---", word_count: 6 },
]
for (let s of test_sentences) {
console.assert(wordcount(s.sentence) === s.word_count, `Expected ${s.word_count} but got ${wordcount(s.sentence)} for "${s.sentence}"`);
}