js查找某个字符串出现了多少次, 快速掌握

js查找某个字符串出现了多少次, 快速掌握

如何查找某个字符串出现了多少次,这是面试中经常被问到的。

话不多说,直接code 一把梭

1. 通过for循环遍历查找


/**
* str { String } 完整字符串
* tatget { String } 目标对象,要查找的字符串
*/
function searchStrEach(str, target) {
    
    
   let sum = 0
   for (let key of str) {
    
    
      if (key == target) {
    
    
         sum ++
      }
   }
   return sum;
 }
 searchStrEach('sdsasads', 'd')

2. 通过数组方法split分割查找


/**
* str { String } 完整字符串
* tatget { String } 目标对象,要查找的字符串
*/
function searchStrSplit(str, target) {
    
    
   return str.split(target).length - 1
}
searchStrSplit('dsfsdfdsfdsfs', 'd')

3. 通过字符串方法indexOf查找

如果不了解indexOf 第二个参数,查看该教程 文档

/**
* str { String } 完整字符串
* tatget { String } 目标对象,要查找的字符串
*/
function fn2(str, target) {
    
    
   let index = str.indexOf(target)
   let sum = 0;
   while(index > -1) {
    
    
      index = str.indexOf(target, index + 1)
      sum ++
   }
   return sum
}
searchStrIndexOf('sdffgfdgw', 'f')

文章如有错误,请各位大佬指正

猜你喜欢

转载自blog.csdn.net/weixin_44165167/article/details/113108032