统计某一字符或字符串在另一个字符串中出现的次数

方法一:使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值