String字符串不使用indexOf方法查找出第一次出现的下标


输入 str1="www.baidu.com"   str2="baidu"

输出  str2在str1中第一次出现的位置,没有则返回-1,如上返回位置4

function findStrIndex (targetStr, findStr) {
  // 要查找的字符串不存在时,返回-1
  if (!findStr) {
    return -1
  }
  // 目标字符串和要查询的字符串相等时,返回起始位置0
  if (targetStr === findStr) {
    return 0
  }
  let length1 = targetStr.length
  let length2 = findStr.length
  // 查询的字符串长度大于目标时,目标肯定不包含被查询的,返回-1
  if (length2 > length1) {
    return -1
  }
  for (let i = 0; i < length1; i++) {
    let str = targetStr.substr(i, length2)
    if (str.length !== findStr.length) {
      return -1
    } else {
      if (targetStr[i] === findStr[0]) {
        // 当循环到目标值中存在 查询值的第一个字符,截取出和查询值一样长度的字符
        // 判断相等则返回下标不相等时继续查找下一个用于判断的字符
        if (!(str === findStr)) {
          continue
        } else {
          return i
        }
      }
    }
  }
}
console.log(findStrIndex('www.baidu.cn', 'asd'))


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM