在段落中使用javascript计数字符串

时间:2011-08-04 04:15:42

标签: javascript

如何计算给定段落中的字符串。

例如: -  我的字符串是“sharepoint 2010”

我的段落是: - sharepoint 2010 很好。 sharepoint 2010 很不错。 sharepoint 2010 比sharepoint 2007更好。

这里计数是: - 3导致sharepoint 2010重复3次

我的问题是使用javascript如何将字符串与段落进行比较。

3 个答案:

答案 0 :(得分:4)

var s = "sharepoint 2010 is good.sharepoint 2010 is nice.sharepoint 2010 is better then sharepoint 2007";
var re = /sharepoint 2010/g;
var c;
for(c = 0; re.exec(s); ++c );
alert(c);

演示:http://jsfiddle.net/Z2jQD/

答案 1 :(得分:3)

只是为了好玩:

<p id="thePara">sharepoint 2010 is good.sharepoint 2010 is nice.sharepoint 2010 is better then sharepoint 2007.</p>

var p = document.getElementById("thePara");
var split = p.innerHTML.split("sharepoint 2010");
alert("length is: " + split[split.length - 1] === "sharepoint 2010" ? split.length : split.length - 1);

演示:http://jsfiddle.net/dKmJY/1/

答案 2 :(得分:2)

试试这个:

var str = "sharepoint 2010 is good.sharepoint 2010 is nice.Sharepoint 2010 is better then sharepoint 2007."; 
var patt1=/sharepoint 2010/gi;
document.write(str.match(patt1).length); //Prints 3