方法一:使用match()方法
// 统计某一字符或字符串在另一个字符串中出现的次数
function countStr(str,target) {
let count = 0
if (!target) {
return count
} else {
// str.match(target) 若数值匹配到,则返回的是一个数组。若匹配不到,则返回null
while(str.match(target)) {
str = str.replace(target, '')
count++
}
return count
}
}
console.log(countStr('22abcfh ab cabc','abc')) // 2
方法二:使用正则
RegExp 对象用于规定在文本中检索的内容
RegExp 是正则表达式的缩写
当您检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp 就是这种模式。
function countStr(str, target) {
if (!target) {
return 0
} else {
console.log(str.match(new RegExp(target, 'g'))) // ["abc", "abc"]
return str.match(new RegExp(target, 'g')).length
}
}
console.log(countStr('22abcfh ab cabc', 'abc')) // 2
RegExp 对象有 3 个方法:test()、exec() 和 compile()
① test() 方法检索字符串中的指定值。
返回值是 true 或 false
var patt1 = new RegExp("best"); document.write(patt1.test("The best things in life are free")); // true
② exec() 方法检索字符串中的指定值。
返回值是被找到的值。如果没有发现匹配,则返回 null。
var patt1 = new RegExp("best"); document.write(patt1.exec("The best things in life are free")); // best
您可以向 RegExp 对象添加第二个参数,以设定检索。例如,如果需要找到所有某个字符的所有存在,则可以使用 "g" 参数 ("global")。
var reg = new RegExp("e", "g"); do { result = reg.exec("The best things in life are free"); document.write(result); } while (result) // eeeeeenull
③ compile() 方法用于改变 RegExp。
compile() 既可以改变检索模式,也可以添加或删除第二个参数。
var reg = new RegExp("e"); reg.compile("d"); document.write(reg.test("The best things in life are free")); // false
方法三:使用字符串分隔方法
// 统计某一字符或字符串在另一个字符串中出现的次数
function countStr(str, target) {
if (!target) {
return 0
} else {
return str.split(target).length - 1
}
}
console.log(countStr('22abcfh ab cabc11', 'abc')) // 2