あなたが書いたアルゴリズムは、これを動作させるために時間を費やしたことを示しています。しかし、それでも動作しない場所はまだまだあります。たとえば、(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と一緒に暮らすあなたの正規表現をテストすることができます。
私は何を男と言うことができますか?私は昨日数時間苦労した。私はコードを完全に理解していませんが、紹介は大きな助けになります!どうもありがとうございます! – sale108