Woorden tellen in string

Ik probeerde op deze manier woorden in een tekst te tellen:

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

Ik denk dat ik dit redelijk goed heb begrepen, behalve dat ik denk dat de if-instructie verkeerd is. Het deel dat controleert of str(i)een spatie bevat en 1 toevoegt

Bewerken:

Ik kwam erachter (dankzij Blender) dat ik dit met veel minder code kan doen:

function WordCount(str) { 
  return str.split(" ").length;
}
console.log(WordCount("hello world"));

Antwoord 1, autoriteit 100%

Gebruik vierkante haken, geen haakjes:

str[i] === " "

Of charAt:

str.charAt(i) === " "

Je zou het ook kunnen doen met .split():

return str.split(' ').length;

Antwoord 2, autoriteit 91%

Probeer deze voordat u de wielen opnieuw uitvindt

van Tel het aantal woorden in een string met JavaScript

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

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

from Gebruik JavaScript om woorden in een string te tellen, ZONDER een regex te gebruiken
– dit is de beste aanpak

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

Opmerkingen van auteur:

Je kunt dit script aanpassen om woorden te tellen op elke gewenste manier.
Het belangrijkste onderdeel is s.split(' ').length— dit telt de
ruimtes.
Het script probeert alle extra spaties (dubbele spaties enz.) te verwijderen voordat het wordt geteld.
Als de tekst twee woorden bevat zonder een spatie ertussen, telt deze als één woord, bijv. “Eerste zin
.Begin van de volgende zin”.


Antwoord 3, autoriteit 20%

Nog een manier om woorden in een string te tellen. Deze code telt woorden die alleen alfanumerieke tekens en tekens “_”, “‘”, “-“, “‘” bevatten.

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

4, Autoriteit 15%

Na het reinigen van de string kunt u niet-witspace-tekens of woordengrenzen matchen.

Hier zijn twee eenvoudige reguliere expressies om woorden in een string vast te leggen:

  • Volgorde van niet-wit-ruimte tekens: /\S+/g
  • Geldige tekens tussen woordgrenzen: /\b[a-z\d]+\b/g

Het onderstaande voorbeeld laat zien hoe het woord tellen van een string ophalen, met behulp van deze vastleggende patronen.

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

Antwoord 5, autoriteit 12%

Ik denk dat deze methode meer is dan je wilt

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

Antwoord 6, autoriteit 7%

String.prototype.matchretourneert een array, we kunnen dan de lengte controleren,

Ik vind deze methode het meest beschrijvend

var str = 'one two three four five';
str.match(/\w+/g).length;

Antwoord 7, autoriteit 4%

De gemakkelijkste manier die ik tot nu toe heb gevonden, is door een regex met split te gebruiken.

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

Antwoord 8, autoriteit 3%

Het antwoord van @7-isnotbad komt heel dicht in de buurt, maar telt geen enkele woordregels. Dit is de oplossing, die elke mogelijke combinatie van woorden, spaties en nieuwe regels lijkt te verklaren.

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

Antwoord 9, autoriteit 3%

Dit zal alle gevallen behandelen en is zo efficiënt mogelijk. (Je wilt geen split(‘ ‘) tenzij je van tevoren weet dat er geen spaties zijn die groter zijn dan één.):

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 = '') {
  return text.split(/\S+/).length - 1;
};
console.log(wordCount(quote));//59
console.log(wordCount('f'));//1
console.log(wordCount('  f '));//1
console.log(wordCount('   '));//0

Antwoord 10, autoriteit 2%

Voor degenen die Lodash willen gebruiken, kunnen de _.wordsfunctie:

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>

Antwoord 11, autoriteit 2%

Hier is mijn aanpak, die een string eenvoudig splitst door spaties, vervolgens de array for-loops geeft en de telling verhoogt als de array[i] overeenkomt met een bepaald regex-patroon.

   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
    }

Zo aangeroepen:

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

(extra tekens en spaties toegevoegd om de nauwkeurigheid van de functie te tonen)

De bovenstaande str retourneert 10, wat correct is!


12, Autoriteit 2%

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

Uitleg:

/([^\u0000-\u007F]|\w)komt overeen met woordtekens – wat geweldig is -> regex doet het zware werk voor ons. (Dit patroon is gebaseerd op het volgende SO-antwoord: https://stackoverflow.com/a/35743562/1806956door @ Landeeyo)

+komt overeen met de hele reeks van de eerder gespecificeerde woordtekens – dus we groeperen in feite woordtekens.

/gbetekent dat het tot het einde blijft zoeken.

str.match(regEx)retourneert een array van de gevonden woorden – dus we tellen de lengte ervan.


Antwoord 13, autoriteit 2%

Nauwkeurigheid is ook belangrijk.

Wat optie 3 doet, is in feite alle witruimten vervangen door een +1en dit vervolgens evalueren om de 1‘s op te tellen, zodat u het aantal woorden krijgt.

Het is de meest nauwkeurige en snelste methode van de vier die ik hier heb gedaan.

Let op: het is langzamer dan return str.split(" ").length;maar het is nauwkeurig in vergelijking met Microsoft Word.

Bekijk bestandsops/s en aantal geretourneerde woorden hieronder.

Hier is een link om deze bench-test uit te voeren.
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.

Antwoord 14

Hier is een functie die het aantal woorden in een HTML-code telt:

$(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

Antwoord 15

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

16

Ik weet niet zeker of dit eerder is gezegd, of als het hier nodig is, maar je de snaar niet een array kunt maken en dan de lengte kunt vinden?

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

17

function countWords(str) {
    str = str.replace(/(^\s*)|(\s*$)/gi,"");
    str = str.replace(/[ ]{2,}/gi," ");
    str = str.replace(/\n /,"\n");
    return str.split(' ').length;
}
document.write(countWords("  this function remove extra space and count the real   string lenth"));

18

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

19

Ik weet dat het laat is, maar deze regex moet je probleem oplossen. Dit komt overeen en retourneert het aantal woorden in uw string. Liever dan degene die je hebt gemarkeerd als een oplossing, die ruimte-ruimte-woord zou tellen als 2 woorden, ook al is het echt slechts 1 woord.

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

20

U hebt fouten in uw code.

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

Er is nog een eenvoudige manier met behulp van reguliere expressies:

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

De exacte waarde kan afwijken van 1 woord, maar het telt ook woordgrenzen zonder ruimte, bijvoorbeeld “woord-woord.woord”. En het telt geen woorden die geen letters of cijfers bevatten.


21

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

22

Ik denk dat dit antwoord alle oplossingen biedt voor:

  1. Aantal tekens in een bepaalde reeks
  2. Aantal woorden in een bepaalde reeks
  3. Aantal lijnen in een bepaalde reeks
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();

23

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

24

Als u specifieke woorden

wilt tellen

function countWholeWords(text, keyword) {
    const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));
    if (times) {
        console.log(`${keyword} occurs ${times.length} times`);
    } else {
        console.log(keyword + " does not occurs")
    }
}
const text = `
In a professional context it often happens that private or corporate clients corder a publication to be 
made and presented with the actual content still not being ready. Think of a news blog that's 
filled with content hourly on the day of going live. However, reviewers tend to be distracted 
by comprehensible content, say, a random text copied from a newspaper or the internet.
`
const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]
wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));
// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times

25

U kunt dit algoritme gebruiken:

app.js:

const TextArea = document.querySelector('textarea');
const CountContainer = document.querySelector('#demo');
TextArea.addEventListener('keypress', () => {
    let TextValue = TextArea.value.split(' ').join('-').split('\n').join('-').split('-');
    let WordCountArray = TextValue.filter(el => {
        return el != '';
    });
    let WordSen = WordCountArray.length <= 1 ? 'Word' : 'Words';
    console.log(WordCountArray);
    CountContainer.textContent = WordCountArray.length + ' ' + WordSen;
});
TextArea.addEventListener('keyup', function () {
    if (this.value === '') CountContainer.textContent = '0 Word';
});

HTML-indexpagina voor test:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <textarea cols="30" rows="10"></textarea>
    <div id="demo"></div>
    <script src="app.js"></script>
</body>
</html>

26

aangepast van internals-in-antwoord
Het behandelt ook de rand van de rand ”

export const countWords = (str: string) => {
  str = str.trim();
  if (!str.length) {
    return str.length
  }
  return str.trim().split(/\s+/).length;
}

JEST-tests

   test("countwords", () => {
        expect(countWords('  ')).toBe(0)
        expect(countWords('78   7 ')).toBe(2)
        expect(countWords('78 7 ')).toBe(2)
        expect(countWords('aa, , 7')).toBe(3)
        expect(countWords('aa, , \n \n \t 7 \n 4')).toBe(4)
    }); 

Antwoord 27

var str =   "Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore illum fuga magni exercitationem porro? Eaque tenetur tempora nesciunt laborum deleniti, quidem nemo consequuntur voluptate alias ad soluta, molestiae, voluptas libero!" ;
let count = (str.match(/\s/g) || []).length;
console.log(count + 1 );
countWords =(str )=>{
    let count =  ( str.match(/\s/g)   || []  ).length;
    count = (count == 0 ) ? 0 : count +1  ; 
    return count 
}

Other episodes