文字列内の単語を数える


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を追加する部分。

編集:

私は(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 2013

8
string.split( '')。lengthが機能しません。スペースは必ずしも単語の境界ではありません!2つの単語の間に複数のスペースがある場合はどうなりますか?「...」はどうですか ?
アロソ2015年

Alosoが言ったように、この方法は機能しません。
現実

1
@ Reality-Torrentこれは古い投稿です。
cst1992 2016年

回答:


107

括弧ではなく角括弧を使用します。

str[i] === " "

またはcharAt

str.charAt(i) === " "

あなたもそれを行うことができます.split()

return str.split(' ').length;

私はあなたが言っていることを理解したと思います編集された元の質問の上記の私のコードは大丈夫ですか?

単語がスペース文字以外で区切られている場合、ソリューションは機能しますか?改行またはタブで言いますか?
nemesisfixx 2016年

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を使用正規表現を使用せず、文字列内の単語をカウントする -これが最善のアプローチとなります

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

著者からのメモ:

このスクリプトを適応させて、好きな方法で単語を数えることができます。重要な部分はs.split(' ').length—これはスペースを数えます。スクリプトは、カウントする前にすべての余分なスペース(ダブルスペースなど)を削除しようとします。テキストにスペースを入れずに2つの単語が含まれている場合、「最初の文。次の文の開始」のように、それらを1つの単語としてカウントします。


私はこの構文を見たことがありません:s = s.replace(/(^ \ s *)|(\ s * $)/ gi、 ""); s = s.replace(/ [] {2、} / gi、 ""); s = s.replace(/ \ n /、 "\ n"); 各行はどういう意味ですか?

何か?このコードは非常に紛らわしく、文字通りコピーして貼り付けたWebサイトはまったく役に立ちません。スペースのない単語をダブルスペースでチェックすることになっているのに、何よりも混乱していますが、どうすればよいでしょうか。ランダムに配置された100万文字だけでは、実際には役に立ちません...

私が求めていたのは、あなたが書いたコードを説明することだけです。私はこれまで構文を見たことがなく、それが何を意味するのか知りたいと思っていました。別の質問をして、誰かが私の質問に深く答えても大丈夫です。たくさんお願いしてすみません。

1
str.split(/ \ s + /)。lengthは、実際にはそのままでは機能しません。末尾の空白は別の単語として扱われます。
イアン

2
空の入力に対して1を返すことに注意してください。
pie6k 2017

21

文字列内の単語を数えるもう1つの方法。このコードは、英数字と「_」、「 '」、「-」、「'」文字のみを含む単語をカウントします。

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

2
’'-「猫の鳴き声」が3語としてカウントされないように追加することも検討してください。そして「中間」
mpen 2018

@mpen提案をありがとう。それに応じて答えを更新しました。
アレックス

文字列の最初の文字は右引用符のFYIであり、バッククォートではありません:-D
mpen 2018

1
’'正規表現で脱出する必要はありません。使用/[\w\d’'-]+/giESLint無無用エスケープ警告を回避するために
ステファンBlamberg

18

文字列をクリーンアップした後、空白以外の文字または単語の境界を一致させることができます。

文字列内の単語をキャプチャするための2つの簡単な正規表現を次に示します。

  • 空白以外の文字のシーケンス: /\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
これは素晴らしく包括的な答えです。すべての例をありがとう、それらは本当に便利です!
コナー2016年

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
文字列が空の場合にエラーが発生する可能性のある場所
PurkhaloAlex19年

5

これまでに見つけた最も簡単な方法は、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

@ 7-isnotbadの答えは非常に近いですが、1語の行はカウントされません。これが修正です。これは、単語、スペース、改行のすべての可能な組み合わせを説明しているようです。

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

これが私のアプローチです。これは、文字列をスペースで分割し、配列をforループして、array [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)

(機能の正確さを示すために余分な文字とスペースを追加しました)

上記のstrは10を返しますが、これは正しいです。


一部の言語はまったく使用[A-Za-z]しません
David

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単語として数えます)それも:

  • 先頭と末尾の空白をすべて無視します

  • カウント単語として新しい行が続く単一文字、 -私はカウントされません、このページで指定された提案のいくつかを見つけた、例えば:
    A
    、A
    、A
    、A
    、A
    、時には0のxの単語としてカウントされますと、他の関数は、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 by @Landeeyo)

+ 以前に指定した単語文字の文字列全体に一致するため、基本的に単語文字をグループ化します。

/g それは最後まで見続けることを意味します。

str.match(regEx) 見つかった単語の配列を返すので、その長さを数えます。


1
複雑な正規表現は魔術の芸術です。私たちが発音を学ぶ呪文ですが、理由を尋ねる勇気はありません。共有してくれてありがとう。
ブレイズ

^それは素晴らしい引用です
r3wt 2018

このエラーが発生します:エラー正規表現の予期しない制御文字:\ x00 no-control-regex
Aliton Oliveira

文字列が/または(
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

これはすべてのケースを処理し、可能な限り効率的です。(1より長いスペースがないことを事前に知っていない限り、split( '')は必要ありません。):

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
このコードスニペットは問題を解決する可能性がありますが、説明を含めると投稿の品質が向上します。あなたは将来読者のために質問に答えていることを忘れないでください、そしてそれらの人々はあなたのコード提案の理由を知らないかもしれません。
isma 2017

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()は静的メソッドです。乾杯。
恥ずかしがり屋のアガム

ええ!承知しました。@ShyAgam
のLiN

1

精度も重要です。

オプション3が行うことは、基本的にすべての空白を除くすべてをaで置き換え、+1これを評価して1'sを、単語数を取得することです。

これは、私がここで行った4つの方法の中で最も正確で最速の方法です。

それはより遅いことに注意してください 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
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の問題をどのように解決しますか?参照:回答する方法。ありがとう!
EduardoBaitello19年

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

私はそれが遅いことを知っていますが、この正規表現はあなたの問題を解決するはずです。これは、文字列内の単語数と一致して返されます。むしろ、ソリューションとしてマークしたものは、実際には1ワードであるにもかかわらず、space-space-wordを2ワードとしてカウントします。

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 2018年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.