查找字符串中特定字符串出现的位置,返回这个位置的索引

时间:2021-01-22 22:14:05
String.prototype.searchCharPosition = function(char, n) {
  if (!this || !char) return -1
  n = n || 1
  var c = 0,
    p = 0
  for (var i = 0; i < this.length; i++) {
    if (char === this[i]) {
      c++
    }
    if (c === n) {
      p = i
      break
    }
  }
  console.log(p)
  return p
}