2017-07-29 5 views
1

フレーズ内の単語の出現回数をカウントする関数を作成しようとしています。単語の出現回数をカウントし、特殊文字と改行を許可する

この機能には、フレーズ内の単語にアルファベット以外の文字および/または行末の文字が追加されている場合も含める必要があります。

function countWordInText(word,phrase){ 
    var c=0; 
    phrase = phrase.concat(" "); 
    regex = (word,/\W/g); 
    var fChar = phrase.indexOf(word); 
    var subPhrase = phrase.slice(fChar); 

    while (regex.test(subPhrase)){ 
     c += 1; 
     subPhrase = subPhrase.slice((fChar+word.length)); 
     fChar = subPhrase.indexOf(word); 
    } 
    return c; 
} 

問題は、単純な値のため、このよう

phrase = "hi hi hi all hi. hi"; 
word = "hi" 
// OR 
word = "hi all"; 

として、それは偽の値を返すことです。

答えて

1

あなたが書いたアルゴリズムは、これを動作させるために時間を費やしたことを示しています。しかし、それでも動作しない場所はまだまだあります。たとえば、(word,/W/g)は実際にあなたが考えるかもしれない正規表現を作成していません。

はるかに簡単な方法もあります:

function countWordInText (word, phrase) { 
    // Escape any characters in `word` that may have a special meaning 
    // in regular expressions. 
    // Taken from https://stackoverflow.com/a/6969486/4220785 
    word = word.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') 

    // Replace any whitespace in `word` with `\s`, which matches any 
    // whitespace character, including line breaks. 
    word = word.replace(/\s+/g, '\\s') 

    // Create a regex with our `word` that will match it as long as it 
    // is surrounded by a word boundary (`\b`). A word boundary is any 
    // character that isn't part of a word, like whitespace or 
    // punctuation. 
    var regex = new RegExp('\\b' + word + '\\b', 'g') 

    // Get all of the matches for `phrase` using our new regex. 
    var matches = phrase.match(regex) 

    // If some matches were found, return how many. Otherwise, return 0. 
    return matches ? matches.length : 0 
} 

countWordInText('hi', 'hi hi hi all hi. hi') // 5 

countWordInText('hi all', 'hi hi hi all hi. hi') // 1 

countWordInText('hi all', 'hi hi hi\nall hi. hi') // 1 

countWordInText('hi all', 'hi hi hi\nalligator hi. hi') // 0 

countWordInText('hi', 'hi himalayas') // 1 

は私が例を通じてコメントを置きます。うまくいけば、これはあなたが始めるのに役立ちます!ここで

はJavaScriptで正規表現を学ぶためにいくつかの素晴らしい場所です:

あなたはまた、Regexrと一緒に暮らすあなたの正規表現をテストすることができます。

+0

私は何を男と言うことができますか?私は昨日数時間苦労した。私はコードを完全に理解していませんが、紹介は大きな助けになります!どうもありがとうございます! – sale108

関連する問題