我创建了一个应该生成一个随机段落的函数,但是我希望得到一些建议,一旦点击按钮,我如何显示段落中每个单词的使用次数....你还有吗?使用像计数器变量这样的东西?
<html>
<head>
<title></title>
<script type="text/javascript">
<!--
var article = ["the", "be", "let", "done", "any"];
var noun = ["boy", "girl", "dog", "town", "car"];
var verb = ["drove","jumped", "ran", "walked", "skipped"];
答案 0 :(得分:1)
使用正则表达式match
,并获取每个搜索单词的结果长度。
例如:
var countThe = sentence.match(/the/g).length;
更新:更一般地说:
function countOccurances(sentence, word){
var reg = RegExp(word,'g');
return sentence.match(reg).length
}
通过测试:
var sentence = "This is the sentence that we are going to look in for testing -- not the real thing." ;
alert(countOccurances(sentence, "the"))
答案 1 :(得分:0)
您可以使用javascript string.match
可能是最简单的方法。
function checkFor(wordsArray,inString){
returnObject={};
for(var i=0;i<wordsArray.length;i++){
returnObject[wordsArray[i]]=inString.match(new RegExp("([^A-Za-z]|^)"+wordsArray[i]+"([^A-Za-z]|$)","gi")).length
}
return returnObject;
}
checkFor(["hi","peter"],"I would like to say to you Peter, hi howdy hello, I think hi is the best of these greetings for you");
Returns Object {hi: 2, peter: 1};
然后在每个数组上运行它,并将sentance作为inString参数
编辑: 为了解释这一点,
/([^A-Za-z]|^)wordGoesHere([^A-Za-z]|$)/gi
,这有点复杂,我承认([^A-Za-z]|^)
检查单词前面的字符不在集合AZ中,或者是否为字符串所以基本上允许空格,逗号,句号和你能想象的任何其他准时的东西。 ([^A-Za-z]|$)
执行相同的操作,除了它检查字符串的结尾This site我发现测试正则表达式非常宝贵
答案 2 :(得分:0)
这将计算字符串中所有单词的频率。
function countWords(s) {
var a = s.match(/\w+/g);
var counts = {};
for(var i = 0; i < a.length; i++) {
var elem = a[i];
if(!counts[elem]) counts[elem] = 1;
else counts[elem]++;
}
return counts;
}