极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何判断字符串包含某个子串

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 555 (opens new window)

String.prototype.includes();
String.prototype.IndexOf = function (searchValue, fromIndex) {
  const string = this;
  const len = string.length;

  // 默认值为 0
  let n = fromIndex | 0;
  // 如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始
  let k = n <= 0 ? 0 : n >= len ? len : n;
  while (k < len) {
    const subStr = string.substring(k, k + searchValue.length);
    if (subStr === searchValue) {
      return k;
    }
    k++;
  }
  return -1;
};

console.log("hello world".IndexOf("ll") + "/" + "hello world".indexOf("ll"));
console.log(
  "hello world".IndexOf("ll", -1) + "/" + "hello world".indexOf("ll", -1)
);
console.log(
  "hello world".IndexOf("or", -6) + "/" + "hello world".indexOf("or", -6)
);
console.log(
  "hello world".IndexOf("wo", 12) + "/" + "hello world".indexOf("wo", 12)
);

Author

回答者: xieyusai (opens new window)

function checkStr(string, child) { let res = string.split(child) if (res.length > 1) return true return false }

Last Updated: 11/4/2022, 6:34:31 PM