Saya mencoba menghitung kata dalam teks dengan cara ini:
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"));
Saya rasa saya telah memahami hal ini dengan cukup baik, kecuali menurut saya if
pernyataan tersebut salah. Bagian yang memeriksa apakah str(i)
berisi spasi dan menambahkan 1.
Edit:
Saya menemukan (berkat Blender) bahwa saya dapat melakukan ini dengan lebih sedikit kode:
function WordCount(str) {
return str.split(" ").length;
}
console.log(WordCount("hello world"));
javascript
Valerio Bozz
sumber
sumber
str.split(' ').length
metode yang lebih mudah? jsfiddle.net/j08691/zUuzdstr.split(' ')
dan kemudian hitung yang bukan string panjang 0?Jawaban:
Gunakan tanda kurung siku, bukan tanda kurung:
str[i] === " "
Atau
charAt
:str.charAt(i) === " "
Anda juga bisa melakukannya dengan
.split()
:return str.split(' ').length;
sumber
Coba ini sebelum menemukan kembali roda
dari Hitung jumlah kata dalam string menggunakan JavaScript
function countWords(str) { return str.trim().split(/\s+/).length; }
dari 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 }
dari Gunakan JavaScript untuk menghitung kata dalam string, TANPA menggunakan regex - ini akan menjadi pendekatan terbaik
function WordCount(str) { return str.split(' ') .filter(function(n) { return n != '' }) .length; }
sumber
Satu cara lagi untuk menghitung kata dalam sebuah string. Kode ini menghitung kata-kata yang hanya berisi karakter alfanumerik dan karakter "_", "'", "-", "'".
function countWords(str) { var matches = str.match(/[\w\d\’\'-]+/gi); return matches ? matches.length : 0; }
sumber
’'-
sehingga "Kucing mengeong" tidak dihitung sebagai 3 kata. Dan "di antara"’'
dalam regex. Gunakan/[\w\d’'-]+/gi
untuk menghindari peringatan no-useless-escapeSetelah membersihkan string, Anda dapat mencocokkan karakter non-spasi atau batas kata.
Berikut dua ekspresi reguler sederhana untuk menangkap kata dalam string:
/\S+/g
/\b[a-z\d]+\b/g
Contoh di bawah ini menunjukkan cara mengambil jumlah kata dari string, dengan menggunakan pola penangkapan ini.
/*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; }
Menemukan Kata-Kata Unik
Anda juga bisa membuat pemetaan kata untuk mendapatkan hitungan unik.
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>
sumber
Saya pikir metode ini lebih dari yang Anda inginkan
var getWordCount = function(v){ var matches = v.match(/\S+/g) ; return matches?matches.length:0; }
sumber
String.prototype.match
mengembalikan array, kita kemudian dapat memeriksa panjangnya,Menurut saya metode ini paling deskriptif
var str = 'one two three four five'; str.match(/\w+/g).length;
sumber
Cara termudah yang saya temukan sejauh ini adalah menggunakan regex dengan 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
sumber
Jawaban yang diberikan oleh @ 7-isnotbad sangat dekat, tetapi tidak menghitung baris satu kata. Berikut perbaikannya, yang tampaknya memperhitungkan setiap kemungkinan kombinasi kata, spasi, dan baris baru.
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; }
sumber
Inilah pendekatan saya, yang hanya membagi string dengan spasi, lalu for loop array dan meningkatkan hitungan jika array [i] cocok dengan pola regex yang diberikan.
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 }
Dipanggil seperti ini:
var str = "testing strings here's a string --.. ? // ... random characters ,,, end of string"; wordCount(str)
(menambahkan karakter & spasi ekstra untuk menunjukkan keakuratan fungsi)
Str di atas mengembalikan 10, yang benar!
sumber
[A-Za-z]
sama sekaliIni akan menangani semua kasus dan seefisien mungkin. (Anda tidak ingin membagi ('') kecuali Anda mengetahui sebelumnya bahwa tidak ada spasi dengan panjang lebih dari satu.):
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
sumber
Mungkin ada cara yang lebih efisien untuk melakukan ini, tetapi inilah yang berhasil bagi saya.
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;
}
itu mampu mengenali semua kata berikut sebagai kata-kata terpisah:
abc,abc
= 2 kata,abc/abc/abc
= 3 kata (bekerja dengan garis miring ke depan dan ke belakang),abc.abc
= 2 kata,abc[abc]abc
= 3 kata,abc;abc
= 2 kata,(beberapa saran lain saya sudah mencoba menghitung setiap contoh di atas hanya sebagai 1 x kata) juga:
mengabaikan semua spasi kosong di depan dan di belakang
jumlah satu huruf diikuti oleh baris baru, sebagai sebuah kata - yang saya telah menemukan beberapa saran yang diberikan di halaman ini tidak dihitung, misalnya:
a
a
a
a
a
kadang-kadang dihitung sebagai 0 x kata-kata, dan fungsi lain hanya menghitungnya sebagai 1 x kata, bukan 5 x kata)
jika ada yang punya ide tentang bagaimana memperbaikinya, atau lebih bersih / lebih efisien - maka tolong tambahkan 2 sen! Semoga Ini Membantu Seseorang.
sumber
function countWords(str) { var regEx = /([^\u0000-\u007F]|\w)+/g; return str.match(regEx).length; }
Penjelasan:
/([^\u0000-\u007F]|\w)
mencocokkan karakter kata - yang hebat -> regex melakukan tugas berat bagi kami. (Pola ini didasarkan pada jawaban SO berikut: https://stackoverflow.com/a/35743562/1806956 oleh @Landeeyo)+
cocok dengan seluruh string dari karakter kata yang ditentukan sebelumnya - jadi pada dasarnya kami mengelompokkan karakter kata./g
Berarti terus mencari sampai akhir.str.match(regEx)
mengembalikan larik kata yang ditemukan - jadi kami menghitung panjangnya.sumber
Bagi yang ingin menggunakan Lodash bisa menggunakan
_.words
fungsi: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>
sumber
Akurasi juga penting.
Apa yang dilakukan opsi 3 pada dasarnya adalah mengganti semua kecuali spasi putih dengan a
+1
dan kemudian mengevaluasi ini untuk menghitung1
memberi Anda jumlah kata.Ini adalah metode paling akurat dan tercepat dari keempat metode yang saya lakukan di sini.
Harap dicatat ini lebih lambat dari
return str.split(" ").length;
tapi akurat jika dibandingkan dengan Microsoft Word.Lihat operasi file dan jumlah kata yang dikembalikan di bawah.
Berikut tautan untuk menjalankan tes bangku ini. 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.
sumber
Inilah fungsi yang menghitung jumlah kata dalam kode HTML:
$(this).val() .replace(/(( )|(<[^>]*>))+/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
sumber
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length
sumber
Saya tidak yakin apakah ini telah dikatakan sebelumnya, atau apakah itu yang dibutuhkan di sini, tetapi tidak bisakah Anda membuat string menjadi sebuah array dan kemudian menemukan panjangnya?
let randomString = "Random String"; let stringWords = randomString.split(' '); console.log(stringWords.length);
sumber
Saya pikir jawaban ini akan memberikan semua solusi untuk:
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();
string.length
string.match(/\w+/g).length
string.length(/\r\n|\r|\n/).length
Saya harap ini dapat membantu mereka yang sedang mencari 3 jawaban tersebut.
sumber
string
menjadi yang lain. Ini membingungkan. Menyebabkan saya berpikir sejenakstring.match()
adalah metode statis. Bersulang.<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>
sumber
Saya tahu ini terlambat tetapi regex ini seharusnya menyelesaikan masalah Anda. Ini akan mencocokkan dan mengembalikan jumlah kata dalam string Anda. Daripada yang Anda tandai sebagai solusi, yang akan menghitung spasi-spasi-kata sebagai 2 kata meskipun sebenarnya hanya 1 kata.
function countWords(str) { var matches = str.match(/\S+/g); return matches ? matches.length : 0; }
sumber
Anda mendapat beberapa kesalahan dalam kode Anda.
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"));
Ada cara mudah lain menggunakan ekspresi reguler:
(text.split(/\b/).length - 1) / 2
Nilai persisnya dapat berbeda sekitar 1 kata, tetapi nilai ini juga menghitung batas kata tanpa spasi, misalnya "kata-kata.word". Dan itu tidak menghitung kata-kata yang tidak mengandung huruf atau angka.
sumber
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());
sumber
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));
sumber