Liczenie słów w łańcuchach


91

Próbowałem policzyć słowa w tekście w ten sposób:

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

Myślę, że całkiem dobrze to zrozumiałem, z wyjątkiem tego, że uważam, że ifstwierdzenie jest błędne. Część, która sprawdza, czy str(i)zawiera spację i dodaje 1.

Edytować:

Dowiedziałem się (dzięki Blenderowi), że mogę to zrobić z dużo mniejszym kodem:

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

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

Nie str.split(' ').lengthbyłaby to łatwiejsza metoda? jsfiddle.net/j08691/zUuzd
j08691

A może str.split(' ')policz te, które nie są ciągami o długości 0?
Katie Kilian,

8
string.split (``) .length nie działa. Spacje nie zawsze są granicami słów! A co, jeśli między dwoma słowami jest więcej niż jedna spacja? Co powiesz na ". . ." ?
Aloso

Jak powiedział Aloso, ta metoda nie zadziała.
Reality-Torrent

1
@ Reality-Torrent To jest stary post.
cst1992,

Odpowiedzi:


107

Użyj nawiasów kwadratowych, a nie nawiasów:

str[i] === " "

Lub charAt:

str.charAt(i) === " "

Możesz to również zrobić za pomocą .split():

return str.split(' ').length;

Myślę, że rozumiem to, co mówisz, czy mój kod w edytowanym oryginalnym pytaniu wygląda dobrze?

czy twoje rozwiązanie zadziała, gdy słowa są oddzielone czymś innym niż znak spacji? Czy mówić przez nowe linie lub karty?
nemesisfixx

7
@Blender dobre rozwiązanie, ale może to dać zły wynik dla podwójnych spacji pominiętych w ciągu ..
ipalibowhyte

95

Wypróbuj je, zanim wymyślisz na nowo koła

od Policz liczbę słów w ciągu za pomocą JavaScript

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

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

z Użyj JavaScript do liczenia słów w ciągu, BEZ użycia wyrażenia regularnego - to będzie najlepsze podejście

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

Uwagi autora:

Możesz dostosować ten skrypt do liczenia słów w dowolny sposób. Ważną częścią jest s.split(' ').lengthto, że liczy się spacje. Skrypt próbuje usunąć wszystkie dodatkowe spacje (podwójne spacje itp.) Przed zliczeniem. Jeśli tekst zawiera dwa słowa bez spacji między nimi, policzy je jako jedno słowo, np. „Pierwsze zdanie .Początek następnego zdania”.


Po prostu nigdy nie widziałem takiej składni: s = s.replace (/ (^ \ s *) | (\ s * $) / gi, ""); s = s.replace (/ [] {2,} / gi, „”); s = s.replace (/ \ n /, "\ n"); co oznacza każda linijka? przepraszam za bycie tak potrzebującym

byle co? ten kod jest bardzo mylący, a witryna, którą dosłownie skopiowałeś i wkleiłeś z niego, nie jest w ogóle pomocna. Jestem po prostu zdezorientowany bardziej niż cokolwiek, co mam, że ma sprawdzać słowa bez spacji, nasze podwójne spacje, ale jak? tylko milion losowo umieszczonych znaków naprawdę nie pomaga ...

To miłe, wszystko, o co prosiłem, to wyjaśnienie kodu, który napisałeś. Nigdy wcześniej nie widziałem składni i chciałem wiedzieć, co ona oznacza. W porządku. Zrobiłem osobne pytanie i ktoś szczegółowo odpowiedział na moje pytanie. Przepraszam, że prosisz o tak wiele.

1
str.split (/ \ s + /). length nie działa tak, jak jest: końcowe białe znaki są traktowane jak inne słowo.
Ian

2
Zauważ, że zwraca 1 dla pustych danych wejściowych.
pie6k

21

Jeszcze jeden sposób liczenia słów w ciągu. Ten kod zlicza słowa, które zawierają tylko znaki alfanumeryczne i znaki "_", "'", "-", "'".

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

2
Można również rozważyć dodanie ’'-, aby „Miauczenie kota” nie liczyło się jako 3 słowa. I „pomiędzy”
mpen

@mpen dzięki za sugestię. Zaktualizowałem swoją odpowiedź zgodnie z nią.
Alex,

Pierwszy znak w moim ciągu to FYI z prawym cudzysłowem, a nie lewy apostrof :-D
mpen

1
Nie musisz uciekać ’'w wyrażeniu regularnym. Użyj, /[\w\d’'-]+/giaby uniknąć ostrzeżeń ESLint o bezużytecznej ucieczce
Stefan Blamberg

18

Po wyczyszczeniu ciągu można dopasować znaki inne niż białe znaki lub granice słów.

Oto dwa proste wyrażenia regularne do przechwytywania słów w ciągu:

  • Sekwencja znaków innych niż białe znaki: /\S+/g
  • Prawidłowe znaki między granicami słów: /\b[a-z\d]+\b/g

Poniższy przykład pokazuje, jak pobrać liczbę słów z ciągu przy użyciu tych wzorców przechwytywania.

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


Znajdowanie wyjątkowych słów

Możesz również utworzyć mapowanie słów, aby uzyskać unikalne liczby.

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
To niesamowita i wyczerpująca odpowiedź. Dzięki za wszystkie przykłady, są naprawdę przydatne!
Connor

14

Myślę, że ta metoda to więcej niż chcesz

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

7

String.prototype.match zwraca tablicę, możemy następnie sprawdzić długość,

Uważam, że ta metoda jest najbardziej opisowa

var str = 'one two three four five';

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

1
potencjalne miejsce wystąpienia błędu, jeśli ciąg jest pusty
Purkhalo Alex

5

Najłatwiejszym sposobem, jaki do tej pory znalazłem, jest użycie wyrażenia regularnego z podziałem.

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

Odpowiedź udzielona przez @ 7-isnotbad jest bardzo bliska, ale nie obejmuje wierszy zawierających pojedyncze słowa. Oto poprawka, która wydaje się uwzględniać każdą możliwą kombinację słów, spacji i znaków nowej linii.

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

Oto moje podejście, które po prostu dzieli ciąg spacjami, a następnie for zapętla tablicę i zwiększa liczbę, jeśli tablica [i] pasuje do podanego wzorca wyrażenia regularnego.

    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
    }

Wywołane tak:

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

(dodano dodatkowe znaki i spacje, aby pokazać dokładność funkcji)

Powyższy str zwraca 10, co jest poprawne!


Niektóre języki nie używają [A-Za-z]w ogóle
David

3

Pozwoli to obsłużyć wszystkie przypadki i będzie tak wydajne, jak to tylko możliwe. (Nie chcesz podzielić (''), chyba że wiesz wcześniej, że nie ma spacji o długości większej niż jeden.):

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

Może istnieć bardziej skuteczny sposób, aby to zrobić, ale to właśnie zadziałało.

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;

}

jest w stanie rozpoznać wszystkie poniższe słowa jako oddzielne słowa:

abc,abc= 2 słowa,
abc/abc/abc= 3 słowa (działa z ukośnikami do przodu i do tyłu),
abc.abc= 2 słowa,
abc[abc]abc= 3 słowa,
abc;abc= 2 słowa,

(kilka innych sugestii, które próbowałem policzyć każdy powyższy przykład jako tylko 1 x słowo), a także:

  • ignoruje wszystkie początkowe i końcowe białe spacje

  • liczy pojedynczą literę, po której następuje nowa linia, jako słowo - które, jak odkryłem, niektóre sugestie podane na tej stronie nie liczą się, na przykład:
    a
    a
    a
    a
    a
    czasami jest liczone jako 0 x słów, i inne funkcje liczą to tylko jako 1 x słowo, zamiast 5 x słów)

jeśli ktoś ma jakieś pomysły jak to ulepszyć lub czyścić / wydajniej - to proszę o dodanie 2 centów! Mam nadzieję, że to komuś pomoże.


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

Wyjaśnienie:

/([^\u0000-\u007F]|\w)dopasowuje znaki słowne - co jest świetne -> regex robi za nas ciężkie zadanie. (Ten wzorzec jest oparty na następującej odpowiedzi SO: https://stackoverflow.com/a/35743562/1806956 autorstwa @Landeeyo)

+ dopasowuje cały ciąg wcześniej określonych znaków słów - więc w zasadzie grupujemy znaki słów.

/g oznacza, że ​​patrzy do końca.

str.match(regEx) zwraca tablicę znalezionych słów - liczymy więc jej długość.


1
Skomplikowane wyrażenie regularne to sztuka magii. Zaklęcie, które uczymy się wymawiać, ale nigdy nie mamy odwagi, by zapytać dlaczego. Dziękuję za udostępnienie.
Blaise,

^ to niesamowity cytat
r3wt

Otrzymuję ten błąd: błąd Nieoczekiwany znak (i) sterujące w wyrażeniu regularnym: \ x00 no-control-regex
Aliton Oliveira

To wyrażenie regularne wyświetli błąd, jeśli ciąg znaków zaczyna się od / lub (
Walter Monecke

@WalterMonecke właśnie przetestował to na Chrome - nie dostał błędu. Gdzie dostałeś błąd z tym? Dzięki
Ronen Rabinovici

2

Dla tych, którzy chcą korzystać z Lodash, mogą skorzystać z _.wordsfunkcji:

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

Ważna jest również dokładność.

Opcja 3 polega w zasadzie na zastąpieniu wszystkich białych spacji poza a, +1a następnie ocenieniu tego w celu zliczenia liczby, 1co daje liczbę słów.

To najdokładniejsza i najszybsza metoda spośród czterech, które tutaj zrobiłem.

Należy pamiętać, że jest wolniejszy niż, return str.split(" ").length;ale dokładny w porównaniu do programu Microsoft Word.

Zobacz poniżej operacje plików i zwróconą liczbę słów.

Oto link do uruchomienia tego testu. 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

Oto funkcja, która zlicza liczbę słów w kodzie 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
Chociaż ten fragment kodu może rozwiązać problem, dołączenie wyjaśnienia naprawdę pomaga poprawić jakość Twojego posta. Pamiętaj, że odpowiadasz na pytanie do czytelników w przyszłości, a osoby te mogą nie znać powodów, dla których zaproponowałeś kod.
Isma

1

Nie jestem pewien, czy zostało to powiedziane wcześniej, czy też jest to potrzebne w tym miejscu, ale czy nie mógłbyś uczynić łańcucha tablicą, a następnie znaleźć długość?

let randomString = "Random String";

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

1

Myślę, że ta odpowiedź da wszystkie rozwiązania dla:

  1. Liczba znaków w podanym ciągu
  2. Liczba słów w podanym ciągu
  3. Liczba wierszy w danym ciągu

 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. Najpierw musisz znaleźć długość podanego ciągu według string.length
  2. Następnie możesz znaleźć liczbę słów, dopasowując je do ciągu string.match(/\w+/g).length
  3. Wreszcie możesz podzielić każdą linię w ten sposób string.length(/\r\n|\r|\n/).length

Mam nadzieję, że pomoże to tym, którzy szukają tych 3 odpowiedzi.


1
Świetny. Zmień nazwę zmiennej stringna inną. To zagmatwane. Przez chwilę pomyślałem, że string.match()to metoda statyczna. Twoje zdrowie.
Shy Agam

Tak!! pewnie. @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
Odpowiedzi zawierające tylko kod są generalnie mile widziane na tej stronie. Czy mógłbyś zmodyfikować swoją odpowiedź, aby zawierała komentarze lub wyjaśnienia dotyczące kodu? Wyjaśnienia powinny odpowiadać na pytania typu: Co to robi? Jak to się dzieje? Dokąd to zmierza? Jak rozwiązuje problem OP? Zobacz: Jak odpowiedzieć . Dzięki!
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

Wiem, że jest późno, ale to wyrażenie regularne powinno rozwiązać Twój problem. To dopasuje i zwróci liczbę słów w ciągu. Raczej ten, który oznaczyłeś jako rozwiązanie, które policzyłoby słowo spacja-spacja jako 2 słowa, mimo że w rzeczywistości jest to tylko 1 słowo.

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

0

Masz kilka błędów w kodzie.

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

Istnieje inny łatwy sposób korzystania z wyrażeń regularnych:

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

Dokładna wartość może różnić się o około 1 słowo, ale uwzględnia również obramowania słów bez spacji, na przykład „słowo-słowo.słowo”. I nie liczy słów, które nie zawierają liter ani cyfr.


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

Dodaj wyjaśnienia edytując odpowiedź, unikaj odpowiedzi tylko kodem
GGO
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.