开发者

Using javascript count string in a Paragraph

How to count a string in a given paragraph.

for example:- my string is "sharepoint 2010"开发者_高级运维

my paragraph is:- sharepoint 2010 is good.sharepoint 2010 is nice.sharepoint 2010 is better then sharepoint 2007.

here count is:- 3 cause sharepoint 2010 repeat 3 times

my problem is using javascript how i compare a string to paragraph.


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);

demo: http://jsfiddle.net/Z2jQD/


Just for fun:

<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);

Demo: http://jsfiddle.net/dKmJY/1/


try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜