计算字符串javascript中的某些单词

时间:2013-12-14 07:07:55

标签: javascript jquery string var

我正在寻找一种方法来计算字符串上的某些单词。

$string = "How are you doing today? You are such a nice person!";

我的目标是计算$ string变量中有多少“是”。

欲望结果:2

7 个答案:

答案 0 :(得分:1)

var string = "are you bare footed?";
console.log(string.split(/\bare\b/).length - 1);

答案 1 :(得分:1)

试试这个:

var count =  yourString.match(/\bare\b/g); 
count = count? count.length : 0;  //checking if there are matches or not.
console.log(count);

答案 2 :(得分:0)

var str = "How are you doing today? You are such a nice person!";
var matchs;
matchs = str.match(/are/gi);
alert(matchs.length);

尝试这个javascript匹配它返回匹配字符串作为数组格式,而length方法返回多少数组索引匹配。

答案 3 :(得分:0)

尝试以下。

    var temp = "How are you doing today? You are such a nice person!.";

var count = countOcurrences(temp,"are");  

alert(count);

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}

答案 4 :(得分:0)

试试这个:

$string = "How are you doing today? You are such a nice person!";

var count = $string.match(/are/g);  

alert(count.length);

答案 5 :(得分:0)

试试这个:

var string = "How are you doing today? You are such a nice person!";
var num = string.match(/are/g).length;
alert(num);

这是Demo

答案 6 :(得分:-1)

你也可以尝试这样的事情:

var temp = "How are you doing today? You are such  a nice person!.";
var arr = [];
for(var i = 0;i< temp.split(' ').length; i++)
{   
    if(temp.split(' ')[i] === "are"){
     arr.push(temp.split(' '));

     }

}
alert(arr.length)