一、基础方法
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方法。 选择何种方法取决于个人偏好和需求,可以根据实际情况选择使用。