您编写的算法表明您花了一些时间试图让它发挥作用。但是,仍然有很多地方不起作用。例如,(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
我在整个示例中都使用了 cmets。希望这可以帮助您入门!
这里有几个学习 Javascript 正则表达式的好地方:
您还可以使用Regexr 实时测试您的正则表达式。