문자열에서 단어 세기


94

이런 식으로 텍스트의 단어를 세려고했습니다.

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 2013-09-08

아니면 str.split(' ')길이가 0이 아닌 문자열을 세나요?
Katie Kilian 2013 년

8
string.split ( '') .length가 작동하지 않습니다. 공백이 항상 단어 테두리는 아닙니다! 두 단어 사이에 공백이 두 개 이상 있으면 어떻게됩니까? 는 어때 ". . ." ?
Aloso 2015-06-26

Aloso가 말했듯이이 방법은 작동하지 않습니다.
현실 - 토런트

1
@ Reality-Torrent 이것은 오래된 게시물입니다.
cst1992

답변:


109

괄호가 아닌 대괄호를 사용하십시오.

str[i] === " "

또는 charAt:

str.charAt(i) === " "

다음과 .split()같이 할 수도 있습니다 .

return str.split(' ').length;

편집 된 원래 질문에서 위의 코드가 괜찮아 보입니까?

귀하의 솔루션은 단어가 공백 문자 이외의 것으로 구분되는 곳에서 작동합니까? 줄 바꿈이나 탭으로 말 하시겠습니까?
nemesisfixx

7
좋은 해결책 @Blender하지만이 .. 문자열에서 생략 더블 공간에 대한 잘못된 결과를 제공 할 수 있습니다
ipalibowhyte

문자열 JavaScript에서 특정 단어의 총량 계산 stackoverflow.com/a/65036248/4752258
Farbod Aprin

96

바퀴를 재발 명하기 전에 이것을 시도하십시오

에서 자바 스크립트를 사용하여 문자열에서 단어의 카운트 수

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 -이것은 공백을 계산합니다. 스크립트는 계산하기 전에 모든 추가 공백 (이중 공백 등)을 제거하려고합니다. 텍스트에 공백없이 두 단어가 포함 된 경우 "첫 번째 문장. 다음 문장의 시작"과 같이 한 단어로 계산됩니다.


이 구문을 본 적이 없습니다. s = s.replace (/ (^ \ s *) | (\ s * $) / gi, ""); s = s.replace (/ [] {2,} / gi, ""); s = s.replace (/ \ n /, "\ n"); 각 줄은 무엇을 의미합니까? 죄송합니다 그래서 가난한 것에 대한

아무것도? 이 코드는 매우 혼란스럽고 문자 그대로 복사하여 붙여 넣은 웹 사이트는 전혀 도움이되지 않습니다. 나는 공백이없는 단어를 확인해야한다는 것보다 더 많은 것을 혼란스럽게 생각하지만 어떻게? 단지 만 무작위로 배치 문자 정말 나던 도움 ...

내가 요청한 것은 당신이 작성한 코드를 설명해 달라는 것뿐입니다. 나는 전에 구문을 본 적이 없으며 그것이 의미하는 바를 알고 싶었습니다. 내가 별도의 질문을했고 누군가가 내 질문에 깊이 답변해도 괜찮습니다. 너무 많이 요청해서 미안합니다.

1
str.split (/ \ s + /). length는 실제로있는 그대로 작동하지 않습니다. 후행 공백은 다른 단어로 처리됩니다.
Ian

2
빈 입력에 대해 1을 반환합니다.
pie6k

21

문자열에서 단어를 세는 또 다른 방법입니다. 이 코드는 영숫자 문자와 "_", " '", "-", "'"문자 만 포함 된 단어를 계산합니다.

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

2
’'-"Cat 's meow"가 3 단어로 계산되지 않도록 추가하는 것도 고려할 수 있습니다. 그리고 "in-between"
mpen 2018-08-02

@mpen 제안에 감사드립니다. 나는 그것에 따라 내 대답을 업데이트했습니다.
Alex

내 문자열의 첫 번째 문자는 백틱이 아닌 오른쪽 인용 FYI입니다. :-D
mpen

1
’'정규식에서 이스케이프 할 필요가 없습니다 . 사용 /[\w\d’'-]+/giESLint없는 쓸모 탈출 경고를 피하기 위해
스테판 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
이것은 훌륭하고 포괄적 인 답변입니다. 모든 예제에 감사드립니다. 정말 유용합니다!
Connor

14

이 방법은 당신이 원하는 것보다 더 많은 것 같아요

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

7

String.prototype.match 배열을 반환하면 길이를 확인할 수 있습니다.

이 방법이 가장 설명 적이라고 생각합니다.

var str = 'one two three four five';

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

1
문자열이 비어 있으면 오류가 발생할 수있는 위치
Purkhalo Alex

5

지금까지 찾은 가장 쉬운 방법은 분할 정규식을 사용하는 것입니다.

var calculate = function() {
  var string = document.getElementById('input').value;
  var length = string.split(/[^\s]+/).length - 1;
  document.getElementById('count').innerHTML = length;
};
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculate()">Calculate</button>
<span id="count">7</span> words


3

@ 7-isnotbad가 제공하는 대답은 매우 가깝지만 한 단어 줄을 계산하지 않습니다. 여기에 단어, 공백 및 줄 바꿈의 가능한 모든 조합을 설명하는 수정 사항이 있습니다.

function countWords(s){
    s = s.replace(/\n/g,' '); // newlines to space
    s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
    return s.split(' ').length; 
}

3

다음은 단순히 문자열을 공백으로 분할 한 다음 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]전혀
데이비드

3

이것은 모든 경우를 처리하고 가능한 한 효율적입니다. (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


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)단어 문자와 일치합니다-대단합니다-> 정규식이 우리를 위해 무거운 작업을 수행합니다. (이 패턴은 @Landeeyo의 https://stackoverflow.com/a/35743562/1806956 SO 답변을 기반으로합니다. )

+ 이전에 지정된 단어 문자의 전체 문자열과 일치하므로 기본적으로 단어 문자를 그룹화합니다.

/g 끝까지 계속보고 있다는 뜻입니다.

str.match(regEx) 발견 된 단어의 배열을 반환하므로 길이를 계산합니다.


1
복잡한 정규식은 요술의 예술입니다. 우리가 발음하는 법을 배우지 만 이유를 물어볼 용기가없는 주문입니다. 공유 해주셔서 감사합니다.
Blaise

^ 그것은 멋진 인용문입니다
r3wt

이 오류가 발생합니다. error Unexpected control character (s) in regular expression : \ x00 no-control-regex
Aliton Oliveira

이 정규식은 문자열이 / 또는 (
Walter Monecke

@WalterMonecke는 방금 크롬에서 테스트했습니다. 오류가 발생하지 않았습니다. 어디에서 오류가 발생 했습니까? 감사합니다
Ronen Rabinovici

2

Lodash를 사용하려는 사람들은 다음 _.words기능 을 사용할 수 있습니다 .

var str = "Random String";
var wordCount = _.size(_.words(str));
console.log(wordCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


2

정확성도 중요합니다.

옵션 3이하는 일은 기본적으로 모든 공백을 a +1로 바꾼 다음이를 평가 1하여 단어 수를 계산하는 것입니다.

제가 여기서 한 네 가지 방법 중 가장 정확하고 빠른 방법입니다.

보다 느립니다. return str.split(" ").length;Microsoft Word와 비교할 만 정확합니다.

아래의 파일 작업 및 반환 된 단어 수를 참조하세요.

이 벤치 테스트를 실행하기위한 링크가 있습니다. https://jsbench.me/ztk2t3q3w5/1

// This is the fastest at 111,037 ops/s ±2.86% fastest
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(" ").length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 2nd fastest at 46,835 ops/s ±1.76% 57.82% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function WordCount(str) {
  return str.split(/(?!\W)\S+/).length;
}
console.log(WordCount(str));
// Returns 241 words. Not the same as Microsoft Word count, of by one.

// This is the 3rd fastest at 37,121 ops/s ±1.18% 66.57% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/\S+/g,"\+1");
  return eval(str);
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.

// This is the slowest at 89 ops/s 17,270 ops/s ±2.29% 84.45% slower
var str = "All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy. All work and no play makes Jack a dull boy.";
function countWords(str) {
  var str = str.replace(/(?!\W)\S+/g,"1").replace(/\s*/g,"");
  return str.lastIndexOf("");
}
console.log(countWords(str));
// Returns 240 words. Same as Microsoft Word count.


1

다음은 HTML 코드에서 단어 수를 계산하는 함수입니다.

$(this).val()
    .replace(/((&nbsp;)|(<[^>]*>))+/g, '') // remove html spaces and tags
    .replace(/\s+/g, ' ') // merge multiple spaces into one
    .trim() // trim ending and beginning spaces (yes, this is needed)
    .match(/\s/g) // find all spaces by regex
    .length // get amount of matches

1
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length

6
이 코드 스 니펫은 질문을 해결할 수 있지만 설명을 포함하면 게시물의 품질을 향상시키는 데 큰 도움이됩니다. 미래에 독자를 위해 질문에 답하고 있으며 해당 사용자는 코드 제안 이유를 모를 수 있습니다.
이스마일

1

이것이 이전에 말했는지 또는 여기에 필요한 것인지 확실하지 않지만 문자열을 배열로 만든 다음 길이를 찾을 수 없습니까?

let randomString = "Random String";

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

1

이 답변이 다음에 대한 모든 솔루션을 제공 할 것이라고 생각합니다.

  1. 주어진 문자열의 문자 수
  2. 주어진 문자열의 단어 수
  3. 주어진 문자열의 줄 수

 function NumberOf() { 
		 var string = "Write a piece of code in any language of your choice that computes the total number of characters, words and lines in a given text. \n This is second line. \n This is third line.";

		 var length = string.length; //No of characters
		 var words = string.match(/\w+/g).length; //No of words
		 var lines = string.split(/\r\n|\r|\n/).length; // No of lines

		 console.log('Number of characters:',length);
		 console.log('Number of words:',words);
		 console.log('Number of lines:',lines);


}

NumberOf();

  1. 먼저 주어진 문자열의 길이를 찾아야합니다. string.length
  2. 그런 다음 문자열과 일치시켜 단어 수를 찾을 수 있습니다. string.match(/\w+/g).length
  3. 마지막으로 다음과 같이 각 줄을 나눌 수 있습니다. string.length(/\r\n|\r|\n/).length

이 세 가지 답변을 찾는 사람들에게 도움이되기를 바랍니다.


1
우수한. 변수 이름 string을 다른 이름 으로 변경하십시오 . 혼란 스럽습니다. 내가 잠시 생각하게 만드는 string.match()것은 정적 방법입니다. 건배.
Shy Agam 19

네!! 확실한. @ShyAgam
LiN

0
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type="text/javascript">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>

0

늦게 알고 있지만이 정규식이 문제를 해결해야합니다. 이것은 일치하고 문자열의 단어 수를 반환합니다. 오히려 당신이 해결책으로 표시 한 것, 그것은 공간-공백 단어를 실제로는 단지 1 개의 단어 임에도 불구하고 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());

답변을 편집 SOMES 설명을 추가하십시오, 피할 코드는 대답
GGO

0
function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 1; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar ++;
        }
    }
    return totalSoFar; 
}
console.log(WordCount("hi my name is raj));

2
이 사이트에서 코드 전용 답변은 일반적으로 눈살을 찌푸립니다. 코드에 대한 설명이나 설명을 포함하도록 답변을 편집 해 주시겠습니까? 설명은 다음과 같은 질문에 답해야합니다. 어떻게하나요? 어디로 갑니까? OP의 문제를 어떻게 해결합니까? 참조 : anwser 방법 . 감사!
Eduardo Baitello 19
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.