JS 简易实现 A是否为B 的子串 的判断函数(不借用原有api)

子串(定义):字符串中任意个连续的字符组成的子序列称为该串的子串。

/**
 * 通过for循环判断A是否为B的子串
 * @param {String} comp - 被对比的字符串(B)
 * @returns {Boolean}
 */
String.prototype.isSubStrOf = function(comp) {
  const str = this.valueOf();

  if (typeof comp !== 'string') {
    if (!(comp instanceof String)) return false;
    comp = comp.valueOf();
  }
  if (str === comp || str === '') return true;

  const compLen = comp.length;
  const len = str.length;
  let index = 0;

  for (let i = 0; i < compLen; i++) {
    if (comp[i] === str[index]) {
      if (index === len - 1) return true;
      index++;
    } else {
      index > 0 ? index-- : (index = 0);
    }
  }

  return false;
}

测试用例

const str = 'abc';
const subStrSet = ['a', 'b', 'c', 'ab', 'bc', 'abc', ''];

subStrSet.every(el => el.isSubStrOf(str)); // true

'ax'.isSubStrOf(str); // false

代码实现如有错误,还望指正