2011-08-04 73 views
0

如何計算給定段落中的字符串。段落中使用javascript count字符串

例如: - 我的字符串爲 「SharePoint 2010的」

我的一段是: - 的SharePoint 2010好。 sharepoint 2010很好。 SharePoint 2010中是優於2007年的SharePoint

這裏計數爲: - 3原因SharePoint 2010中重複3次

我的問題,我如何比較字符串以段落使用JavaScript。

回答

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/

+0

THX卡里姆它的工作。 –

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/

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