Đếm từ trong chuỗi


91

Tôi đang cố gắng đếm các từ trong một văn bản theo cách này:

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

Tôi nghĩ rằng tôi đã giải quyết vấn đề này khá tốt, ngoại trừ tôi nghĩ rằng iftuyên bố đó là sai. Phần kiểm tra xem str(i)có chứa khoảng trắng hay không và thêm 1.

Biên tập:

Tôi phát hiện ra (nhờ Blender) rằng tôi có thể làm điều này với ít mã hơn:

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

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

Sẽ không phải str.split(' ').lengthlà một phương pháp dễ dàng hơn? jsfiddle.net/j08691/zUuzd
j08691

Hoặc str.split(' ')và sau đó đếm những cái không phải là 0 chuỗi độ dài?
Katie Kilian

8
string.split ('') .length không hoạt động. Dấu cách không phải lúc nào cũng là đường viền từ! Điều gì xảy ra nếu có nhiều hơn một khoảng trắng giữa hai từ? Thế còn ". . ." ?
Aloso

Như Aloso đã nói, phương pháp này sẽ không hoạt động.
Thực tế-Torrent

1
@ Reality-Torrent Đây là một bài đăng cũ.
cst1992

Câu trả lời:


107

Sử dụng dấu ngoặc vuông, không phải dấu ngoặc đơn:

str[i] === " "

Hoặc charAt:

str.charAt(i) === " "

Bạn cũng có thể làm điều đó với .split():

return str.split(' ').length;

Tôi nghĩ rằng tôi đã hiểu những gì bạn đang nói, mã của tôi ở trên trong câu hỏi ban đầu đã chỉnh sửa trông ổn chứ?

giải pháp của bạn sẽ hoạt động khi các từ được phân tách bằng bất kỳ thứ gì khác ngoài ký tự khoảng trắng? Nói bằng dòng mới hoặc tab?
nemesisfixx

7
@Blender giải pháp tốt nhưng điều này có thể cho kết quả sai cho không gian hai bỏ qua trong một chuỗi ..
ipalibowhyte

95

Hãy thử những điều này trước khi phát minh lại bánh xe

từ Đếm số từ trong chuỗi bằng JavaScript

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

từ 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
}

từ Sử dụng JavaScript để đếm các từ trong một chuỗi, KHÔNG sử dụng regex - đây sẽ là cách tiếp cận tốt nhất

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

Ghi chú từ tác giả:

Bạn có thể điều chỉnh tập lệnh này để đếm từ theo bất kỳ cách nào bạn thích. Phần quan trọng là s.split(' ').length- điều này đếm khoảng cách. Tập lệnh cố gắng loại bỏ tất cả các dấu cách thừa (dấu cách kép, v.v.) trước khi đếm. Nếu văn bản chứa hai từ không có khoảng cách giữa chúng, nó sẽ tính chúng là một từ, ví dụ: "Câu đầu tiên. Bắt đầu câu tiếp theo".


Tôi chưa bao giờ thấy cú pháp này: s = s.replace (/ (^ \ s *) | (\ s * $) / gi, ""); s = s.replace (/ [] {2,} / gi, ""); s = s.replace (/ \ n /, "\ n"); mỗi dòng có nghĩa là gì? xin lỗi vì quá nghèo

bất cứ điều gì? mã này rất khó hiểu và trang web mà bạn sao chép và dán từ nó theo nghĩa đen không hữu ích chút nào. Tôi chỉ nhầm lẫn nhiều hơn bất cứ điều gì Tôi hiểu rằng nó phải kiểm tra các từ không có dấu cách dấu cách đôi của chúng ta nhưng làm thế nào? chỉ là một triệu ký tự đặt một cách ngẫu nhiên giúp đỡ thực sự doesnt ...

Thật tuyệt, tất cả những gì tôi yêu cầu là bạn giải thích mã bạn đã viết. Tôi chưa bao giờ nhìn thấy cú pháp trước đây và muốn biết nó có nghĩa là gì. Không sao, tôi đã đặt một câu hỏi riêng và ai đó đã trả lời câu hỏi của tôi chuyên sâu. Xin lỗi vì đã yêu cầu rất nhiều.

1
str.split (/ \ s + /). length không thực sự hoạt động như hiện tại: khoảng trắng ở cuối được coi như một từ khác.
Ian

2
Lưu ý rằng nó trả về 1 cho đầu vào trống.
pie6k

21

Thêm một cách để đếm số từ trong một chuỗi. Mã này đếm các từ chỉ chứa các ký tự chữ và số và các ký tự "_", "'", "-", "'".

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

2
Cũng có thể cân nhắc thêm ’'-để "Cat's meo" không được tính là 3 từ. Và "ở giữa"
mpen

@mpen cảm ơn đã gợi ý. Tôi đã cập nhật câu trả lời của mình theo nó.
Alex

Char đầu tiên trong chuỗi của tôi là một quyền-quote FYI, không phải là một backtick :-D
mpen

1
Bạn không cần phải trốn thoát ’'trong một regex. Sử dụng /[\w\d’'-]+/giđể tránh ESLint cảnh báo không-vô-escape
Stefan Blamberg

18

Sau khi làm sạch chuỗi, bạn có thể khớp các ký tự không có khoảng trắng hoặc ranh giới từ.

Dưới đây là hai biểu thức chính quy đơn giản để nắm bắt các từ trong một chuỗi:

  • Chuỗi ký tự không phải khoảng trắng: /\S+/g
  • Các ký tự hợp lệ giữa các ranh giới từ: /\b[a-z\d]+\b/g

Ví dụ dưới đây cho thấy cách truy xuất số lượng từ từ một chuỗi, bằng cách sử dụng các mẫu thu thập này.

/*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; }


Tìm từ duy nhất

Bạn cũng có thể tạo ánh xạ các từ để có được số lượng duy nhất.

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
Đây là một câu trả lời tuyệt vời và toàn diện. Cảm ơn vì tất cả các ví dụ, chúng thực sự hữu ích!
Connor

14

Tôi nghĩ rằng phương pháp này nhiều hơn bạn muốn

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

7

String.prototype.match trả về một mảng, sau đó chúng ta có thể kiểm tra độ dài,

Tôi thấy phương pháp này là mô tả nhất

var str = 'one two three four five';

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

1
nơi tiềm năng để xảy ra một lỗi nếu chuỗi rỗng
Purkhalo Alex

5

Cách dễ nhất mà tôi tìm thấy cho đến nay là sử dụng một regex với tách.

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

Câu trả lời được đưa ra bởi @ 7-isnotbad là cực kỳ gần, nhưng không tính các dòng gồm một từ. Đây là cách khắc phục, dường như tính đến mọi sự kết hợp có thể có của từ, khoảng trắng và dòng mới.

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

Đây là cách tiếp cận của tôi, chỉ đơn giản là chia một chuỗi theo dấu cách, sau đó cho các vòng lặp của mảng và tăng số lượng nếu mảng [i] khớp với một mẫu regex nhất định.

    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
    }

Được gọi như vậy:

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

(đã thêm các ký tự & khoảng trắng bổ sung để hiển thị độ chính xác của hàm)

Str ở trên trả về 10, đúng!


Một số ngôn ngữ không sử dụng [A-Za-z]ở tất cả
David

2

Có thể có một cách hiệu quả hơn để làm điều này, nhưng đây là những gì đã làm việc cho tôi.

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;

}

nó có thể nhận ra tất cả những điều sau là các từ riêng biệt:

abc,abc= 2 từ,
abc/abc/abc= 3 từ (hoạt động với dấu gạch chéo tiến và lùi),
abc.abc= 2 từ,
abc[abc]abc= 3 từ,
abc;abc= 2 từ,

(một số gợi ý khác mà tôi đã thử đếm mỗi ví dụ ở trên chỉ là 1 x từ) nó cũng:

  • bỏ qua tất cả các khoảng trắng ở đầu và cuối

  • đếm một chữ cái đơn lẻ theo sau là một dòng mới, như một từ - mà tôi thấy một số gợi ý được đưa ra trên trang này không được tính, ví dụ:
    a
    a
    a
    a
    a
    đôi khi được tính là 0 x từ và các hàm khác chỉ tính nó là 1 x từ, thay vì 5 x từ)

nếu ai đó có bất kỳ ý tưởng nào về cách cải thiện nó, hoặc sạch hơn / hiệu quả hơn - vui lòng thêm cho bạn 2 xu! Mong rằng nó giúp ai đó thoát.


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

Giải trình:

/([^\u0000-\u007F]|\w)khớp các ký tự từ - điều đó thật tuyệt -> regex thực hiện công việc nặng nhọc cho chúng ta. (Mẫu này dựa trên câu trả lời SO sau: https://stackoverflow.com/a/35743562/1806956 bởi @Landeeyo)

+ khớp với toàn bộ chuỗi ký tự từ đã chỉ định trước đó - vì vậy về cơ bản chúng tôi nhóm các ký tự từ.

/g có nghĩa là nó tiếp tục tìm kiếm cho đến cùng.

str.match(regEx) trả về một mảng các từ tìm được - vì vậy chúng tôi đếm độ dài của nó.


1
Regex phức tạp là nghệ thuật phù thủy. Một câu thần chú mà chúng ta học cách phát âm, nhưng không bao giờ có can đảm để hỏi tại sao. Cảm ơn bạn đã chia sẻ.
Blaise

^ đó là một câu trích dẫn tuyệt vời
r3wt 21/09/18

Tôi gặp lỗi này: lỗi (Các) ký tự điều khiển không mong muốn trong biểu thức chính quy: \ x00 no-control-regex
Aliton Oliveira

Regex này sẽ phát sinh lỗi nếu chuỗi bắt đầu bằng / hoặc (
Walter Monecke

@WalterMonecke vừa thử nghiệm nó trên chrome - không gặp lỗi. Bạn gặp lỗi ở đâu với điều này? Cảm ơn
Ronen Rabinovici

2

Đối với những người muốn sử dụng Lodash có thể sử dụng _.wordschức năng:

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

Điều này sẽ xử lý tất cả các trường hợp và hiệu quả nhất có thể. (Bạn không muốn tách ('') trừ khi bạn biết trước rằng không có khoảng trắng nào có độ dài lớn hơn một.):

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

Đây là một hàm đếm số từ trong mã 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
Mặc dù đoạn mã này có thể giải quyết câu hỏi, bao gồm một lời giải thích thực sự giúp cải thiện chất lượng bài đăng của bạn. Hãy nhớ rằng bạn đang trả lời câu hỏi cho người đọc trong tương lai và những người đó có thể không biết lý do cho đề xuất mã của bạn.
Isma

1

Tôi không chắc liệu điều này đã được nói trước đây chưa, hay đó là thứ cần thiết ở đây, nhưng bạn không thể tạo chuỗi thành một mảng và sau đó tìm độ dài?

let randomString = "Random String";

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

1

Tôi nghĩ câu trả lời này sẽ cung cấp tất cả các giải pháp cho:

  1. Số ký tự trong một chuỗi nhất định
  2. Số từ trong một chuỗi nhất định
  3. Số dòng trong một chuỗi nhất định

 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. Trước tiên, bạn cần tìm độ dài của chuỗi đã cho bằng string.length
  2. Sau đó, bạn có thể tìm số từ bằng cách kết hợp chúng với chuỗi string.match(/\w+/g).length
  3. Cuối cùng bạn có thể chia từng dòng như thế này string.length(/\r\n|\r|\n/).length

Tôi hy vọng điều này có thể giúp những người đang tìm kiếm 3 câu trả lời này.


1
Thông minh. Vui lòng thay đổi tên biến thành tên stringkhác. Thật khó hiểu. Khiến tôi nghĩ trong giây lát string.match()là một phương pháp tĩnh. Chúc mừng.
Shy Agam

vâng !! chắc chắn rồi. @ShyAgam
Lin

1

Độ chính xác cũng rất quan trọng.

Những gì tùy chọn 3 làm về cơ bản là thay thế tất cả trừ bất kỳ khoảng trắng nào bằng a +1và sau đó đánh giá điều này để đếm số từ 1mang lại cho bạn.

Đó là phương pháp chính xác nhất và nhanh nhất trong bốn phương pháp mà tôi đã làm ở đây.

Xin lưu ý rằng nó chậm hơn return str.split(" ").length;nhưng nó chính xác khi so sánh với Microsoft Word.

Xem hoạt động của tệp và số từ được trả về bên dưới.

Đây là một liên kết để chạy thử nghiệm băng ghế dự bị này. 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
Các câu trả lời chỉ có mã thường được đưa ra trên trang web này. Bạn có thể vui lòng chỉnh sửa câu trả lời của mình để bao gồm một số nhận xét hoặc giải thích về mã của bạn không? Phần giải thích nên trả lời những câu hỏi như: Nó làm gì? Nó làm điều đó như thế nào? Nó đi đâu? Nó giải quyết vấn đề của OP như thế nào? Xem: Làm thế nào để anwser . Cảm ơn!
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

Tôi biết nó muộn nhưng regex này sẽ giải quyết vấn đề của bạn. Điều này sẽ khớp và trả về số lượng từ trong chuỗi của bạn. Thay vào đó, từ bạn đã đánh dấu là một giải pháp, sẽ tính khoảng trắng-dấu cách-từ là 2 từ mặc dù nó thực sự chỉ là 1 từ.

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

0

Bạn có một số lỗi trong mã của mình.

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

Có một cách dễ dàng khác bằng cách sử dụng biểu thức chính quy:

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

Giá trị chính xác có thể khác nhau khoảng 1 từ, nhưng nó cũng tính các đường viền từ không có khoảng trắng, ví dụ: "word-word.word". Và nó không đếm những từ không chứa chữ cái hoặc số.


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

Vui lòng thêm Somes giải thích chỉnh sửa câu trả lời của bạn, mã tránh chỉ trả lời
GGO
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.