स्ट्रिंग में शब्दों की गिनती


91

मैं एक पाठ में शब्दों को इस तरह गिनने की कोशिश कर रहा था:

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 जोड़ता है।

संपादित करें:

मुझे पता चला (ब्लेंडर के लिए धन्यवाद) कि मैं बहुत कम कोड के साथ ऐसा कर सकता हूं:

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

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

str.split(' ').lengthएक आसान तरीका नहीं होगा ? jsfiddle.net/j08691/zUuzd
— j08691

या str.split(' ')फिर उन लोगों की गणना करें जो 0 लंबाई के तार नहीं हैं?
— केटी किलियन

8
string.split ('') .length काम नहीं करती। रिक्तियाँ हमेशा शब्द सीमा नहीं होती हैं! यदि दो शब्दों के बीच एक से अधिक स्थान हो तो क्या होगा? व्हाट अबाउट "। । ।" ?
— एलोसो

जैसा कि अलसो ने कहा, यह तरीका काम नहीं करेगा।
— रियलिटी-टॉरेंट

1
@ हकीकत-धार यह एक पुरानी पोस्ट है।
— cst1992

जवाबों:


107

वर्ग कोष्ठक का उपयोग करें, कोष्ठक का नहीं:

str[i] === " "

या charAt:

str.charAt(i) === " "

आप इसके साथ भी कर सकते हैं .split():

return str.split(' ').length;

मुझे लगता है कि मुझे वही मिला है जो आप कह रहे हैं कि संपादित मूल प्रश्न में मेरा कोड ऊपर ठीक है?

क्या आपका समाधान कार्य करेगा जहाँ शब्दों को अंतरिक्ष वर्ण के अलावा किसी अन्य चीज़ द्वारा सीमांकित किया गया है? Newlines या टैब द्वारा कहें?
— nemesisfixx

7
@ अच्छा समाधान लेकिन यह एक स्ट्रिंग में छोड़े गए दोहरे स्थानों के लिए गलत परिणाम दे सकता है ..
— ipalibowhyte

95

पहियों को सुदृढ़ करने से पहले इन्हें आज़माएं

से जावास्क्रिप्ट का उपयोग स्ट्रिंग में शब्दों की गणना संख्या

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
}

से उपयोग जावास्क्रिप्ट, एक स्ट्रिंग में शब्दों की गिनती करने के लिए रेगुलर एक्सप्रेशन का उपयोग किए बिना - यह सबसे अच्छा तरीका हो सकता है

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

लेखक से नोट्स:

आप इस स्क्रिप्ट को शब्दों को गिनने के लिए अनुकूलित कर सकते हैं जो भी आपको पसंद हो। महत्वपूर्ण हिस्सा है s.split(' ').length- यह रिक्त स्थान को गिनता है। स्क्रिप्ट गिनती से पहले सभी अतिरिक्त रिक्त स्थान (डबल रिक्त स्थान आदि) को निकालने का प्रयास करती है। यदि पाठ में उनके बीच की जगह के बिना दो शब्द हैं, तो यह उन्हें एक शब्द के रूप में गिना जाएगा, उदाहरण के लिए "पहला वाक्य। अगले वाक्य की शुरुआत।"


Ive सिर्फ इस वाक्यविन्यास को कभी नहीं देखा है: s = s.replace (/ (^ \ s *) | ((\ s * $) / gi, ""); s = s.replace (/ [[] {2,} / गी, ""); s = s.replace (/ \ n /, "\ n"); प्रत्येक पंक्ति का क्या अर्थ है? इतना ज़रूरतमंद होने के लिए खेद है

कुछ भी? यह कोड बहुत ही भ्रामक है और यह वेबसाइट जिसे आपने शाब्दिक रूप से कॉपी किया है और इससे चिपकाया है, बिल्कुल भी मददगार नहीं है। Im बस कुछ भी नहीं है कि मैं अपने डबल रिक्त स्थान के बिना शब्दों के लिए जाँच करने के लिए माना जाता है, लेकिन कैसे? बस एक लाख बेतरतीब ढंग से रखे गए पात्र वास्तव में मदद नहीं करते ...

Thats अच्छा सब मैं पूछ रहा था कि आप अपने कोड को समझाने के लिए आप लिखा है। Ive पहले सिंटैक्स को कभी नहीं देखा था और जानना चाहता था कि इसका क्या मतलब है। यह ठीक है मैंने एक अलग सवाल किया और किसी ने मेरे सवाल का गहराई से जवाब दिया। इतना पूछने के लिए क्षमा करें।

1
str.split (/ \ s + /)। लंबाई वास्तव में के रूप में काम नहीं करती है: सफेद स्थान को पीछे छोड़ते हुए दूसरे शब्द के रूप में माना जाता है।
— इयान

2
ध्यान दें कि यह खाली इनपुट के लिए 1 रिटर्न देता है।
— --०१

21

एक स्ट्रिंग में शब्दों को गिनने का एक और तरीका। यह कोड उन शब्दों को गिनता है जिनमें केवल अल्फ़ान्यूमेरिक वर्ण और "_", "'", "-", "" "वर्ण होते हैं।

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

2
इसे जोड़ने पर भी विचार करें ’'-ताकि "बिल्ली की म्याऊ" की गिनती 3 शब्दों के रूप में न हो। और "इन-इन-बीच"
— एमपीएन

@ सुझाव के लिए धन्यवाद। मैंने इसके अनुसार अपना उत्तर अपडेट कर दिया है।
— एलेक्स

मेरी स्ट्रिंग में पहला
— चार्ट

1
आप ’'एक regex में भागने की जरूरत नहीं है । /[\w\d’'-]+/giESLint से बचने के लिए उपयोग करें बेकार-भागने की चेतावनियाँ
— 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
संभावित स्थान त्रुटि होने पर यदि स्ट्रिंग खाली है
— पुरखो एलेक्स

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] दिए गए रेगेक्स पैटर्न से मेल खाती है।

    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)

(अतिरिक्त सटीकता और फ़ंक्शन की सटीकता दिखाने के लिए रिक्त स्थान जोड़े गए)

ऊपर वाला रिटर्न 10 देता है, जो सही है!


कुछ भाषाओं का उपयोग नहीं करते [A-Za-z]हैं
— डेविड

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 एक्स शब्द के रूप में गिना जाता है, और अन्य कार्य केवल 5 x शब्दों के बजाय इसे 1 x शब्द के रूप में गिनते हैं)

अगर किसी के पास इसे सुधारने के बारे में कोई विचार है, या क्लीनर / अधिक कुशल है - तो कृपया आपको 2 सेंट जोड़ें! आशा है कि यह किसी की मदद करता है।


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

स्पष्टीकरण:

/([^\u0000-\u007F]|\w)शब्द वर्णों से मेल खाता है - जो महान है -> रेगेक्स हमारे लिए भारी उठाने का काम करता है। (यह पैटर्न निम्नलिखित SO उत्तर पर आधारित है: https://stackoverflow.com/a/35743562/1806956 @Landeeyo द्वारा)

+ पहले निर्दिष्ट शब्द वर्णों के पूरे स्ट्रिंग से मेल खाता है - इसलिए हम मूल रूप से शब्द वर्णों को समूहित करते हैं।

/g इसका मतलब यह अंत तक देखता रहता है।

str.match(regEx) पाए गए शब्दों की एक सरणी देता है - इसलिए हम इसकी लंबाई गिनते हैं।


1
जटिल रेगेक्स जादू टोना की कला है। एक मंत्र जो हम उच्चारण करना सीखते हैं, लेकिन कभी भी हिम्मत क्यों नहीं होती। साझा करने के लिए धन्यवाद।
— Blaise

^ यह एक भयानक उद्धरण है
— r3wt

मुझे यह त्रुटि मिल रही है: त्रुटि अनपेक्षित नियंत्रण वर्ण (ओं) को नियमित अभिव्यक्ति में: \ x00 नो-कंट्रोल-रेगेक्स
— एलिटोन ओलिवेरा

यदि स्ट्रिंग / / (
— वाल्टर मोनेके

@AlterMonecke ने सिर्फ क्रोम पर इसका परीक्षण किया - त्रुटि नहीं मिली। आपको इसमें कहां त्रुटि हुई? धन्यवाद
— रोनेन Rabinovici

2

उन लोगों के लिए जो लॉडश का उपयोग करना चाहते हैं, वे _.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

यह सभी मामलों को संभाल लेगा और यथासंभव कुशल होगा। (आप विभाजित नहीं करना चाहते ('') जब तक आप पहले से नहीं जानते कि एक से अधिक लंबाई के स्थान नहीं हैं।)

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

यहां एक फ़ंक्शन है जो 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()एक स्थिर विधि है। चीयर्स।
— श्‍याम अगम

हाँ !! ज़रूर। @ श्यागाम
— LiN

1

सटीकता भी महत्वपूर्ण है।

विकल्प 3 क्या करता है, मूल रूप से सभी व्हाट्सएप को एक के साथ बदल देता है +1और फिर इसे गिनने के लिए इसका मूल्यांकन करता है1 आपको शब्द की गिनती देने के लिए करता है।

यह मेरे द्वारा किए गए चार में से सबसे सटीक और सबसे तेज़ तरीका है।

कृपया ध्यान दें कि return str.split(" ").length;यह माइक्रोसॉफ्ट वर्ड की तुलना में धीमी है, लेकिन सटीक है।

फ़ाइल 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
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
इस साइट पर कोड-ओनली उत्तर आमतौर पर दिए गए हैं। क्या आप अपने जवाब को अपने कोड की कुछ टिप्पणियों या स्पष्टीकरण को शामिल करने के लिए संपादित कर सकते हैं? स्पष्टीकरण में सवालों का जवाब देना चाहिए जैसे: यह क्या करता है? इसे यह कैसे करना है? यह कहाँ जाता है? यह ओपी की समस्या को कैसे हल करता है? देखें: कैसे anwser के लिए । धन्यवाद!
— एडुआर्डो बैइटेलो

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 को आपकी समस्या का समाधान करना चाहिए। यह आपके स्ट्रिंग में शब्दों की संख्या से मेल खाएगा और लौटाएगा। बल्कि तब जिसे आपने एक समाधान के रूप में चिह्नित किया था, जो अंतरिक्ष-शब्द-शब्द को 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 शब्द के बारे में भिन्न हो सकता है, लेकिन यह अंतरिक्ष के बिना शब्द सीमाओं को भी गिनता है, उदाहरण के लिए "शब्द-शब्द.शब्द"। और यह उन शब्दों को नहीं गिनता जिनमें अक्षर या संख्याएँ नहीं हैं।


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
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.