76 javascript
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"));
Run Code Online (Sandbox Code Playgroud)
我认为我已经很好地解决了这个问题,除了我认为这个if说法是错误的.怎么说if(str(i)包含空格,加1.
编辑:
我发现(感谢Blender)我可以用更少的代码来做到这一点:
function WordCount(str) {
return str.split(" ").length;
}
console.log(WordCount("hello world"));
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 87
使用方括号,而不是括号:
str[i] === " "
Run Code Online (Sandbox Code Playgroud)
或者charAt:
str.charAt(i) === " "
Run Code Online (Sandbox Code Playgroud)
您也可以这样做.split():
return str.split(' ').length;
Run Code Online (Sandbox Code Playgroud)
7-i*_*bad 79
在重新发明轮子之前尝试这些
function countWords(str) {
return str.trim().split(/\s+/).length;
}
Run Code Online (Sandbox Code Playgroud)
来自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
}
Run Code Online (Sandbox Code Playgroud)
从使用JavaScript来算的话在一个字符串中,不使用正则表达式 -这将是最好的方法
function WordCount(str) {
return str.split(' ')
.filter(function(n) { return n != '' })
.length;
}
Run Code Online (Sandbox Code Playgroud)
来自作者的注释:
您可以调整此脚本以您喜欢的方式计算单词.重要的是
s.split(' ').length- 这会计算空间.脚本尝试在计数之前删除所有额外的空格(双空格等).如果文本包含两个单词之间没有空格,则将它们计为一个单词,例如"第一句.下一句的开头".
Ale*_*lex 17
另一种计算字符串中单词的方法.此代码计算仅包含字母数字字符和"_","'"," - ","'"字符的单词.
function countWords(str) {
var matches = str.match(/[\w\d\’\'-]+/gi);
return matches ? matches.length : 0;
}
Run Code Online (Sandbox Code Playgroud)
Mr.*_*irl 16
清理字符串后,您可以匹配非空白字符或字边界.
以下是两个简单的正则表达式来捕获字符串中的单词:
/\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(', ')));Run Code Online (Sandbox Code Playgroud)
body { font-family: monospace; white-space: pre; font-size: 11px; }Run Code Online (Sandbox Code Playgroud)
您还可以创建单词映射以获取唯一计数.
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);
});
});Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
Sea*_*ean 14
我认为这种方法比你想要的多
var getWordCount = function(v){
var matches = v.match(/\S+/g) ;
return matches?matches.length:0;
}
Run Code Online (Sandbox Code Playgroud)
这一行代码非常简单,即使单词之间有多个空格,它也能准确地计算单词数:
return string.split(/\s+/).length;
Run Code Online (Sandbox Code Playgroud)
| 部分表达 | 解释 |
|---|---|
\s |
匹配任何空白字符 |
+ |
匹配前一个令牌一次到无限次 |
到目前为止,我找到的最简单的方法是使用带有split的正则表达式。
var calculate = function() {
var string = document.getElementById('input').value;
var length = string.split(/[^\s]+/).length - 1;
document.getElementById('count').innerHTML = length;
};Run Code Online (Sandbox Code Playgroud)
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculate()">Calculate</button>
<span id="count">7</span> wordsRun Code Online (Sandbox Code Playgroud)
String.prototype.match 返回一个数组,然后我们可以检查长度,
我发现这种方法最具描述性
var str = 'one two three four five';
str.match(/\w+/g).length;
Run Code Online (Sandbox Code Playgroud)
@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;
}
Run Code Online (Sandbox Code Playgroud)
这将处理所有情况并且尽可能高效。(除非您事先知道没有长度大于 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
Run Code Online (Sandbox Code Playgroud)