/*计算子字符串在字符中出现的次数*/
//字符串
var str1 = 'zhulinjia zh lia tjqig qgx gja xx yy xxf xxxq wqja ix'
//子串
var str2 = 'a'
alert( Tongji(str1 , str2) )
//统计
function Tongji(string , char)
{
var index = 0 , index1 = 0 , count = 0
for(var i = 0i <string.length &&( index1 !dao= -1 )i++ )
{
index1 = string.indexOf(char, index)
index = index1 + 1
count = i
}
return count
}
可以利用正则表达式进程获取:
var str = "abbbbbsdsdsdasdlsfj"var c = "b" // 要计算的字符
var regex = new RegExp(c, 'g') // 使用g表示整个字符串都要匹配
var result = str.match(regex)
var count = !result ? 0 : result.length
console.log(c + " 的数量为 " + count)