Conteggio delle parole in stringa


91

Stavo cercando di contare le parole in un testo in questo modo:

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

Penso di aver capito abbastanza bene, tranne che penso che l' ifaffermazione sia sbagliata. La parte che controlla se str(i)contiene uno spazio e aggiunge 1.

Modificare:

Ho scoperto (grazie a Blender) che posso farlo con molto meno codice:

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

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

Non str.split(' ').lengthsarebbe un metodo più semplice? jsfiddle.net/j08691/zUuzd
j08691

O str.split(' ')e poi contare quelli che non sono stringhe di lunghezza 0?
Katie Kilian

8
string.split ('') .length non funziona. Gli spazi non sono sempre confini di parole! E se c'è più di uno spazio tra due parole? Che dire ". . ." ?
Aloso

Come ha detto Aloso, questo metodo non funzionerà.
Reality-Torrent

1
@ Reality-Torrent Questo è un vecchio post.
cst1992

Risposte:


107

Usa parentesi quadre, non parentesi:

str[i] === " "

Oppure charAt:

str.charAt(i) === " "

Puoi anche farlo con .split():

return str.split(' ').length;

Penso di aver capito quello che stai dicendo: il mio codice sopra nella domanda originale modificata sembra ok?

la tua soluzione funzionerebbe dove le parole sono delimitate da qualcosa di diverso dal carattere spazio? Dì per newline o tabulazioni?
nemesisfixx

7
@Blender buona soluzione ma questo può dare il risultato sbagliato per i doppi spazi omessi in una stringa ..
ipalibowhyte

95

Provali prima di reinventare le ruote

from Contare il numero di parole nella stringa utilizzando JavaScript

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

da 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
}

da Usa JavaScript per contare le parole in una stringa, SENZA usare un'espressione regolare: questo sarà l'approccio migliore

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

Note dell'autore:

Puoi adattare questo script per contare le parole nel modo che preferisci. La parte importante è s.split(' ').length: questo conta gli spazi. Lo script tenta di rimuovere tutti gli spazi extra (doppi spazi ecc.) Prima di contare. Se il testo contiene due parole senza uno spazio tra di loro, le conterà come una parola, ad esempio "Prima frase. Inizio della frase successiva".


Non ho mai visto questa sintassi: s = s.replace (/ (^ \ s *) | (\ s * $) / gi, ""); s = s.replace (/ [] {2,} / gi, ""); s = s.replace (/ \ n /, "\ n"); cosa significa ogni riga? scusa per essere così bisognoso

nulla? questo codice è molto confuso e il sito Web che hai letteralmente copiato e incollato non è affatto utile. Sono solo confuso più di ogni altra cosa, capisco che dovrebbe controllare le parole senza spazi i nostri doppi spazi, ma come? solo un milione di caratteri posizionati a caso non aiuta davvero ...

È carino tutto ciò che ti chiedevo è di spiegare il codice che hai scritto. Non ho mai visto la sintassi prima e volevo sapere cosa significasse. Va bene, ho fatto una domanda separata e qualcuno ha risposto alla mia domanda in modo approfondito. Scusa per aver chiesto così tanto.

1
str.split (/ \ s + /). length non funziona davvero così com'è: lo spazio vuoto finale viene trattato come un'altra parola.
Ian

2
Nota che restituisce 1 per un input vuoto.
pie6k

21

Un altro modo per contare le parole in una stringa. Questo codice conta le parole che contengono solo caratteri alfanumerici e caratteri "_", "'", "-", "'".

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

2
Potresti anche considerare di aggiungere in ’'-modo che "Miao di gatto" non conti come 3 parole. E "in-between"
mpen

@mpen grazie per il suggerimento. Ho aggiornato la mia risposta in base ad essa.
Alex

Il primo carattere nella mia stringa è una citazione giusta FYI, non un backtick :-D
mpen

1
Non è necessario eseguire l'escape ’'in una regex. Utilizzare /[\w\d’'-]+/giper evitare gli avvisi di fuga inutili di
ESLint

18

Dopo aver pulito la stringa, puoi trovare la corrispondenza tra caratteri diversi da spazi o limiti di parole.

Ecco due semplici espressioni regolari per catturare le parole in una stringa:

  • Sequenza di caratteri non spazi vuoti: /\S+/g
  • Caratteri validi tra i confini delle parole: /\b[a-z\d]+\b/g

L'esempio seguente mostra come recuperare il conteggio delle parole da una stringa, utilizzando questi modelli di acquisizione.

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


Trovare parole uniche

Puoi anche creare una mappatura di parole per ottenere conteggi unici.

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
Questa è una risposta fantastica e completa. Grazie per tutti gli esempi, sono davvero utili!
Connor

14

Penso che questo metodo sia più di quanto vuoi

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

7

String.prototype.match restituisce un array, possiamo quindi controllare la lunghezza,

Trovo che questo metodo sia molto descrittivo

var str = 'one two three four five';

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

1
luogo potenziale in cui si verifica un errore se la stringa è vuota
Purkhalo Alex

5

Il modo più semplice che ho trovato finora è usare una regex con 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


3

La risposta data da @ 7-isnotbad è estremamente vicina, ma non conta le righe di una sola parola. Ecco la soluzione, che sembra tenere conto di ogni possibile combinazione di parole, spazi e nuove righe.

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

Ecco il mio approccio, che divide semplicemente una stringa per spazi, quindi for esegue il ciclo dell'array e aumenta il conteggio se l'array [i] corrisponde a un determinato pattern 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
    }

Invocato in questo modo:

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

(aggiunti caratteri e spazi extra per mostrare l'accuratezza della funzione)

La stringa sopra restituisce 10, che è corretto!


Alcune lingue non usano [A-Za-z]affatto
David il

3

Questo gestirà tutti i casi ed è il più efficiente possibile. (Non vuoi dividere ('') a meno che tu non sappia in anticipo che non ci sono spazi di lunghezza maggiore di uno.):

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

Potrebbe esserci un modo più efficiente per farlo, ma questo è ciò che ha funzionato per me.

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;

}

è in grado di riconoscere tutto quanto segue come parole separate:

abc,abc= 2 parole,
abc/abc/abc= 3 parole (funziona con barre avanti e indietro),
abc.abc= 2 parole,
abc[abc]abc= 3 parole,
abc;abc= 2 parole,

(alcuni altri suggerimenti che ho provato a contare ogni esempio sopra come solo 1 x parola) inoltre:

  • ignora tutti gli spazi bianchi iniziali e finali

  • conta una singola lettera seguita da una nuova riga, come una parola - che ho trovato che alcuni dei suggerimenti forniti in questa pagina non contano, ad esempio:
    a
    a
    a
    a
    a a
    volte viene contata come 0 x parole, e altre funzioni lo contano solo come 1 x parola, invece di 5 x parole)

se qualcuno ha qualche idea su come migliorarlo, o più pulito / più efficiente, allora aggiungi 2 centesimi! Spero che questo aiuti qualcuno.


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

Spiegazione:

/([^\u0000-\u007F]|\w)corrisponde ai caratteri delle parole - il che è fantastico -> regex fa il lavoro pesante per noi. (Questo modello si basa sulla seguente risposta SO: https://stackoverflow.com/a/35743562/1806956 di @Landeeyo)

+ corrisponde all'intera stringa dei caratteri delle parole specificati in precedenza, quindi fondamentalmente raggruppiamo i caratteri delle parole.

/g significa che continua a cercare fino alla fine.

str.match(regEx) restituisce un array delle parole trovate, quindi ne contiamo la lunghezza.


1
L'espressione regolare complicata è l'arte della stregoneria. Un incantesimo che impariamo a pronunciare, ma non abbiamo mai il coraggio di chiedere un perché. Grazie per aver condiviso.
Blaise

^ questa è una citazione fantastica
r3wt

Ricevo questo errore: errore Caratteri di controllo imprevisti nell'espressione regolare: \ x00 no-control-regex
Aliton Oliveira

Questa regex creerà un errore se la stringa inizia con / o (
Walter Monecke il

@WalterMonecke lo ha appena testato su Chrome - non ha ricevuto l'errore. Dove hai ricevuto un errore con questo? Grazie
Ronen Rabinovici

2

Per chi vuole utilizzare Lodash può utilizzare la _.wordsfunzione:

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

Anche la precisione è importante.

Quello che fa l'opzione 3 è fondamentalmente sostituire tutti gli spazi tranne eventuali spazi bianchi con una +1e quindi valuta questo per contare il1 che ti dà il conteggio delle parole.

È il metodo più accurato e veloce dei quattro che ho fatto qui.

Tieni presente che è più lento di return str.split(" ").length; ma è accurato rispetto a Microsoft Word.

Vedi file ops / s e numero di parole restituite di seguito.

Ecco un collegamento per eseguire questo test al banco. 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

Ecco una funzione che conta il numero di parole in un codice 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
Sebbene questo frammento di codice possa risolvere la domanda, includere una spiegazione aiuta davvero a migliorare la qualità del tuo post. Ricorda che stai rispondendo alla domanda per i lettori in futuro e quelle persone potrebbero non conoscere i motivi del tuo suggerimento sul codice.
Isma

1

Non sono sicuro se questo sia stato detto in precedenza, o se è ciò che è necessario qui, ma non potresti rendere la stringa un array e quindi trovare la lunghezza?

let randomString = "Random String";

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

1

Penso che questa risposta fornirà tutte le soluzioni per:

  1. Numero di caratteri in una data stringa
  2. Numero di parole in una data stringa
  3. Numero di righe in una data stringa

 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. Per prima cosa devi trovare la lunghezza della stringa data da string.length
  2. Quindi puoi trovare il numero di parole abbinandole a una stringa string.match(/\w+/g).length
  3. Finalmente puoi dividere ogni riga in questo modo string.length(/\r\n|\r|\n/).length

Spero che questo possa aiutare coloro che stanno cercando queste 3 risposte.


1
Eccellente. Si prega di modificare il nome della variabile stringin qualcos'altro. È confusionario. Mi ha fatto pensare per un secondo string.match()è un metodo statico. Saluti.
Timido Agam

si!! sicuro. @ShyAgam
LiN

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
Le risposte di solo codice sono generalmente disapprovate su questo sito. Potresti modificare la tua risposta per includere alcuni commenti o una spiegazione del tuo codice? Le spiegazioni dovrebbero rispondere a domande come: cosa fa? Come lo fa? Dove va? Come risolve il problema di OP? Vedi: Come rispondere . Grazie!
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

So che è tardi ma questa regex dovrebbe risolvere il tuo problema. Questo corrisponderà e restituirà il numero di parole nella stringa. Piuttosto quindi quello che hai contrassegnato come soluzione, che conterebbe spazio-spazio-parola come 2 parole anche se in realtà è solo 1 parola.

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

0

Hai degli errori nel codice.

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'è un altro modo semplice per usare le espressioni regolari:

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

Il valore esatto può differire di circa 1 parola, ma conta anche i bordi delle parole senza spazio, ad esempio "parola-parola.parola". E non conta le parole che non contengono lettere o numeri.


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

Si prega di aggiungere alcune spiegazioni modificando la risposta, evitare la risposta solo codice
GGO
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.