การนับคำในสตริง


93

ฉันพยายามนับคำในข้อความด้วยวิธีนี้:

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

คงstr.split(' ').lengthเป็นวิธีที่ง่ายกว่านี้มิใช่หรือ? jsfiddle.net/j08691/zUuzd
j08691

หรือstr.split(' ')แล้วนับคนที่ไม่ใช่สตริงความยาว 0?
Katie Kilian

8
string.split ('') .length ไม่ทำงาน ช่องว่างไม่ใช่พรมแดนคำเสมอไป! จะเกิดอะไรขึ้นถ้ามีช่องว่างมากกว่าหนึ่งช่องระหว่างสองคำ? แล้ว "..." เหรอ?
Aloso

ดังที่ Aloso กล่าววิธีนี้จะไม่ได้ผล
Reality-Torrent

1
@ Reality-Torrent นี่เป็นกระทู้เก่า
cst1992

คำตอบ:


109

ใช้วงเล็บเหลี่ยมไม่ใช่วงเล็บ:

str[i] === " "

หรือcharAt:

str.charAt(i) === " "

คุณสามารถทำได้ด้วย.split():

return str.split(' ').length;

ฉันคิดว่าฉันเข้าใจในสิ่งที่คุณพูดแล้วโค้ดของฉันข้างบนในคำถามต้นฉบับที่แก้ไขนั้นดูโอเคไหม

โซลูชันของคุณจะใช้งานได้หรือไม่โดยที่คำถูกคั่นด้วยสิ่งอื่นที่ไม่ใช่อักขระเว้นวรรค พูดตามบรรทัดใหม่หรือแท็บ?
nemesisfixx

7
@Blender วิธีแก้ปัญหาที่ดี แต่อาจให้ผลลัพธ์ที่ผิดสำหรับช่องว่างสองชั้นที่ละไว้ในสตริง ..
ipalibowhyte

95

ลองใช้สิ่งเหล่านี้ก่อนที่จะสร้างล้อใหม่

จากการนับจำนวนคำในสตริงโดยใช้ 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 เพื่อนับคำในสตริงโดยไม่ต้องใช้ regex - นี่จะเป็นแนวทางที่ดีที่สุด

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

หมายเหตุจากผู้เขียน:

คุณสามารถปรับสคริปต์นี้เพื่อนับจำนวนคำได้ตามที่คุณต้องการ ส่วนที่สำคัญคือs.split(' ').length- นับช่องว่าง สคริปต์พยายามลบช่องว่างพิเศษทั้งหมด (ช่องว่างคู่ ฯลฯ ) ก่อนที่จะนับ หากข้อความมีคำสองคำโดยไม่มีช่องว่างระหว่างคำก็จะนับเป็นคำเดียวเช่น "ประโยคแรกเริ่มประโยคถัดไป"


ฉันไม่เคยเห็นไวยากรณ์นี้: s = s.replace (/ (^ \ s *) | (\ s * $) / gi, ""); s = s.replace (/ [] {2,} / gi, ""); s = s.replace (/ \ n /, "\ n"); แต่ละบรรทัดหมายถึงอะไร? ขอโทษที่ขัดสนมาก

อะไร? รหัสนี้สับสนมากและเว็บไซต์นั้นที่คุณคัดลอกและวางจากมันไม่เป็นประโยชน์เลย ฉันแค่สับสนมากกว่าสิ่งใดที่ฉันเข้าใจว่ามันควรจะตรวจสอบคำโดยไม่เว้นวรรคสองช่องของเรา แต่อย่างไร? ตัวละครที่วางแบบสุ่มเพียงล้านตัวช่วยไม่ได้จริงๆ ...

นั่นเป็นสิ่งที่ดีทั้งหมดที่ฉันขอคือให้คุณอธิบายรหัสของคุณที่คุณเขียน ฉันไม่เคยเห็นไวยากรณ์มาก่อนและอยากรู้ว่ามันหมายถึงอะไร เป็นเรื่องปกติฉันตั้งคำถามแยกกันและมีคนตอบคำถามของฉันในเชิงลึก ขออภัยที่ถามมาก

1
str.split (/ \ s + /) ความยาวใช้ไม่ได้จริงตามที่เป็นอยู่: ช่องว่างต่อท้ายจะถือว่าเป็นคำอื่น
เอียน

2
หมายเหตุจะส่งคืน 1 สำหรับอินพุตว่าง
pie6k

21

อีกวิธีหนึ่งในการนับจำนวนคำในสตริง รหัสนี้นับคำที่มีเฉพาะอักขระที่เป็นตัวอักษรและตัวเลขคละกันและอักขระ "_", "'", "-", "'"

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

2
อาจพิจารณาเพิ่ม’'-เพื่อไม่ให้ "แมวเหมียว" นับเป็น 3 คำ และ "ระหว่าง"
mpen

@mpen ขอบคุณสำหรับข้อเสนอแนะ ฉันได้อัปเดตคำตอบของฉันตามนั้น
Alex

อักขระตัวแรกในสตริงของฉันคือ FYI ที่อ้างสิทธิ์ไม่ใช่แบ็คทิก :-D
mpen

1
คุณไม่จำเป็นต้องหลบหนี’'ใน regex ใช้/[\w\d’'-]+/giเพื่อหลีกเลี่ยงคำเตือน ESLint no-useless-escape
Stefan Blamberg

18

หลังจากทำความสะอาดสตริงแล้วคุณสามารถจับคู่อักขระที่ไม่ใช่ช่องว่างหรือขอบเขตของคำได้

นี่คือสองนิพจน์ทั่วไปง่ายๆในการจับคำในสตริง:

  • ลำดับของอักขระที่ไม่ใช่ช่องว่าง: /\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>


1
นี่คือคำตอบที่ยอดเยี่ยมและครอบคลุม ขอบคุณสำหรับตัวอย่างทั้งหมดมีประโยชน์มาก!
คอนเนอร์

14

ฉันคิดว่าวิธีนี้เป็นมากกว่าที่คุณต้องการ

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

7

String.prototype.match ส่งคืนอาร์เรย์จากนั้นเราสามารถตรวจสอบความยาว

ฉันพบว่าวิธีนี้มีความหมายมากที่สุด

var str = 'one two three four five';

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

1
สถานที่ที่อาจเกิดข้อผิดพลาดหากสตริงว่างเปล่า
Purkhalo Alex

5

วิธีที่ง่ายที่สุดที่ฉันพบคือใช้นิพจน์ทั่วไปกับการแยก

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

คำตอบที่ได้จาก @ 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; 
}

3

นี่คือแนวทางของฉันซึ่งเพียงแค่แยกสตริงด้วยช่องว่างจากนั้นสำหรับการวนซ้ำอาร์เรย์และเพิ่มจำนวนหากอาร์เรย์ [i] ตรงกับรูปแบบ regex ที่กำหนด

    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 ซึ่งถูกต้อง!


บางภาษาไม่ได้ใช้[A-Za-z]เลย
David

3

วิธีนี้จะจัดการกับทุกกรณีและมีประสิทธิภาพมากที่สุด (คุณไม่ต้องการแยก ('') เว้นแต่คุณจะรู้ล่วงหน้าว่าไม่มีช่องว่างที่มีความยาวมากกว่าหนึ่งช่อง):

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

2

อาจมีวิธีที่มีประสิทธิภาพมากกว่านี้ แต่นี่คือสิ่งที่ได้ผลสำหรับฉัน

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 x คำ) นอกจากนี้:

  • ละเว้นช่องว่างสีขาวที่นำหน้าและต่อท้ายทั้งหมด

  • นับเป็นหนึ่งเดียวตัวอักษรตามด้วยบรรทัดใหม่เป็นคำ - ที่ฉันได้พบบางส่วนของข้อเสนอแนะที่ได้รับในหน้านี้จะไม่นับรวมตัวอย่างเช่น: บางครั้งได้รับนับเป็น 0 x คำและ ฟังก์ชั่นอื่น ๆ จะนับเป็น 1 x word แทน 5 x word)







หากใครมีความคิดในการปรับปรุงหรือสะอาด / มีประสิทธิภาพมากขึ้น - กรุณาเพิ่ม 2 เซ็นต์! หวังว่านี่จะช่วยใครบางคนได้


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

คำอธิบาย:

/([^\u0000-\u007F]|\w)ตรงกับอักขระคำ - ซึ่งดีมาก -> regex ช่วยยกระดับให้เรา (รูปแบบนี้มาจากคำตอบ SO ต่อไปนี้: https://stackoverflow.com/a/35743562/1806956โดย @Landeeyo)

+ จับคู่สตริงทั้งหมดของอักขระคำที่ระบุไว้ก่อนหน้านี้ดังนั้นเราจึงจัดกลุ่มอักขระคำโดยทั่วไป

/g หมายความว่าจะดูต่อไปจนจบ

str.match(regEx) ส่งคืนอาร์เรย์ของคำที่พบ - ดังนั้นเราจึงนับความยาว


1
นิพจน์ทั่วไปที่ซับซ้อนเป็นศิลปะแห่งเวทมนตร์ คาถาที่เราเรียนรู้ที่จะออกเสียง แต่ไม่เคยมีความกล้าที่จะถามว่าทำไม ขอบคุณสำหรับการแชร์.
Blaise

^ นั่นเป็นคำพูดที่ยอดเยี่ยม
r3wt

ฉันได้รับข้อผิดพลาดนี้: เกิดข้อผิดพลาดอักขระควบคุมที่ไม่คาดคิดในนิพจน์ทั่วไป: \ x00 no-control-regex
Aliton Oliveira

regex นี้จะแสดงข้อผิดพลาดหากสตริงเริ่มต้นด้วย / หรือ (
Walter Monecke

@WalterMonecke เพิ่งทดสอบบน Chrome - ไม่ได้รับข้อผิดพลาด คุณได้รับข้อผิดพลาดจากที่ใด ขอบคุณ
Ronen Rabinovici

2

สำหรับผู้ที่ต้องการใช้ 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>


2

ความแม่นยำก็สำคัญเช่นกัน

สิ่งที่ตัวเลือก 3 ทำโดยพื้นฐานแล้วจะแทนที่ช่องว่างทั้งหมดยกเว้นช่องว่างใด ๆ ด้วย a +1แล้วประเมินสิ่งนี้เพื่อนับจำนวน1คำที่ให้คุณ

เป็นวิธีที่แม่นยำและเร็วที่สุดในสี่วิธีที่ฉันเคยทำที่นี่

โปรดทราบว่ามันช้ากว่า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.


1

นี่คือฟังก์ชันที่นับจำนวนคำในโค้ด 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
แม้ว่าข้อมูลโค้ดนี้จะช่วยแก้ปัญหาได้ แต่การมีคำอธิบายจะช่วยปรับปรุงคุณภาพของโพสต์ของคุณได้มาก โปรดจำไว้ว่าคุณกำลังตอบคำถามสำหรับผู้อ่านในอนาคตและบุคคลเหล่านั้นอาจไม่ทราบสาเหตุของการแนะนำโค้ดของคุณ
อิสมา

1

ฉันไม่แน่ใจว่าสิ่งนี้ได้พูดไปก่อนหน้านี้หรือว่าเป็นสิ่งที่จำเป็นที่นี่ แต่คุณไม่สามารถสร้างสตริงเป็นอาร์เรย์แล้วหาความยาว

let randomString = "Random String";

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

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

ฉันหวังว่านี่จะสามารถช่วยผู้ที่กำลังค้นหาคำตอบทั้ง 3 ข้อนี้


1
ยอดเยี่ยม. โปรดเปลี่ยนชื่อตัวแปรstringเป็นอย่างอื่น มันสับสน ทำให้ฉันคิดเป็นครั้งที่สองstring.match()เป็นวิธีการคงที่ ไชโย
Shy Agam

ใช่!! แน่นอน. @ShyAgam
LiN

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

ฉันรู้ว่ามันช้าไป แต่ regex นี้ควรแก้ปัญหาของคุณ สิ่งนี้จะจับคู่และส่งกลับจำนวนคำในสตริงของคุณ แทนที่จะเป็นคำที่คุณทำเครื่องหมายว่าเป็นคำตอบซึ่งจะนับ space-space-word เป็น 2 คำแม้ว่าจะมีเพียง 1 คำก็ตาม

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

0

คุณมีข้อผิดพลาดบางอย่างในรหัสของคุณ

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" และไม่นับคำที่ไม่มีตัวอักษรหรือตัวเลข


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

โปรดเพิ่มคำอธิบายในการแก้ไขคำตอบของคุณหลีกเลี่ยงคำตอบเฉพาะรหัส
GGO

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

2
โดยทั่วไปคำตอบที่ใช้รหัสเท่านั้นจะอยู่ในเว็บไซต์นี้ คุณช่วยแก้ไขคำตอบของคุณให้มีความคิดเห็นหรือคำอธิบายโค้ดของคุณได้ไหม คำอธิบายควรตอบคำถามเช่น: มันทำอะไร? มันทำได้อย่างไร? ไม่ไปไหน วิธีแก้ปัญหาของ OP ดู: วิธีการ Anwser ขอบคุณ!
Eduardo Baitello
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.