30秒学会 JavaScript 片段 · 2023年12月15日

30秒学会 JavaScript 片段 – Case-insensitive substring search

Checks if a string contains a substring, case-insensitive.

  • Use the RegExp constructor with the 'i' flag to create a regular expression, that matches the given searchString, ignoring the case.
  • Use RegExp.prototype.test() to check if the string contains the substring.

代码实现

const includesCaseInsensitive = (str, searchString) =>
  new RegExp(searchString, 'i').test(str);

includesCaseInsensitive('Blue Whale', 'blue'); // true

翻译自:https://www.30secondsofcode.org/js/s/includes-case-insensitive