JS判斷字符串中是否包含某個字符串

一、基礎方法

function basicIncludes(str, subStr) {
  return str.includes(subStr);
}

可以直接使用JavaScript中的includes方法來判斷一個字符串是否包含另外一個字符串。

使用方法:

const str = 'This is a string';
const subStr = 'is';
const isIncluded = basicIncludes(str, subStr);
console.log(isIncluded); // true

二、indexOf方法

function indexOfMethod(str, subStr) {
  return str.indexOf(subStr) !== -1;
}

可以使用字符串的indexOf方法來判斷一個字符串是否包含在另外一個字符串中。

使用方法:

const str = 'This is a string';
const subStr = 'is';
const isIncluded = indexOfMethod(str, subStr);
console.log(isIncluded); // true

三、正則表達式

function regexMethod(str, subStr) {
  const regex = new RegExp(subStr, 'g');
  return regex.test(str);
}

可以使用正則表達式來判斷一個字符串是否包含在另外一個字符串中。

使用方法:

const str = 'This is a string';
const subStr = 'is';
const isIncluded = regexMethod(str, subStr);
console.log(isIncluded); // true

四、ES6 includes方法

function es6Includes(str, subStr) {
  return str.includes(subStr);
}

可以使用ES6中新增的includes方法來判斷一個字符串是否包含在另外一個字符串中。

使用方法:

const str = 'This is a string';
const subStr = 'is';
const isIncluded = es6Includes(str, subStr);
console.log(isIncluded); // true

五、lodash庫的includes方法

function lodashIncludes(str, subStr) {
  return _.includes(str, subStr);
}

可以使用lodash庫中的includes方法來判斷一個字符串是否包含在另外一個字符串中。

使用方法:

const str = 'This is a string';
const subStr = 'is';
const isIncluded = lodashIncludes(str, subStr);
console.log(isIncluded); // true

結束語

以上就是JS判斷字符串中是否包含某個字符串的幾種方法,包括基礎方法、indexOf方法、正則表達式、ES6 includes方法以及lodash庫中的includes方法。

選擇何種方法取決於個人偏好和需求,可以根據實際情況選擇使用。

原創文章,作者:VUBBA,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/313377.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
VUBBA的頭像VUBBA
上一篇 2025-01-07 09:43
下一篇 2025-01-07 09:43

相關推薦

發表回復

登錄後才能評論