JS字符串包含

在JavaScript中,字符串是一种基本的数据类型,用于存储文本数据。在实际开发中,经常会遇到需要判断一个字符串是否包含另一个字符串的情况。这时我们可以使用字符串的包含方法来实现。本文将详细介绍JS中字符串包含的方法及相关用例。
includes()方法
在ES6中,新增了一个字符串方法includes(),用于判断一个字符串是否包含另一个字符串。这个方法返回一个布尔值,表示被查找的字符串是否在原字符串中。
语法
str.includes(searchString[, position])
searchString:要搜索的子字符串。position:可选参数,表示从原字符串的哪个位置开始搜索。
示例
let str = 'Hello, world!';
console.log(str.includes('Hello')); // true
console.log(str.includes('World')); // false
console.log(str.includes('world')); // true
上面的示例中,我们用includes()方法来判断字符串str是否包含'Hello'、'World'和'world',并输出相关结果。
indexOf()方法
除了includes()方法外,我们也可以使用indexOf()方法来判断一个字符串是否包含另一个字符串。indexOf()方法会返回被搜索的子字符串在原字符串中的位置,如果没有找到返回-1。
语法
str.indexOf(searchValue[, fromIndex])
searchValue:要搜索的子字符串。fromIndex:可选参数,表示搜索的起始位置。
示例
let str = 'Hello, world!';
console.log(str.indexOf('Hello')); // 0
console.log(str.indexOf('World')); // -1
console.log(str.indexOf('world')); // 7
在上面的示例中,我们用indexOf()方法来判断字符串str中是否包含'Hello'、'World'和'world',并输出相关结果。
startsWith()和endsWith()方法
除了判断字符串是否包含另一个字符串,我们还可以使用startsWith()和endsWith()方法来判断字符串是否以某个子字符串开头或结尾。
startsWith()方法
startsWith()方法用于判断字符串是否以指定的子字符串开头,返回布尔值。
语法
str.startsWith(searchString[, position])
searchString:要搜索的子字符串。position:可选参数,表示从原字符串的哪个位置开始搜索。
示例
let str = 'Hello, world!';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('World')); // false
console.log(str.startsWith('world', 7)); // true
在上面的示例中,我们用startsWith()方法来判断字符串str是否以'Hello'、'World'和'world'开头,并输出相关结果。
endsWith()方法
endsWith()方法用于判断字符串是否以指定的子字符串结尾,返回布尔值。
语法
str.endsWith(searchString[, length])
searchString:要搜索的子字符串。length:可选参数,表示从原字符串的哪个位置开始搜索。
示例
let str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('World!')); // false
console.log(str.endsWith('Hello', 5)); // true
在上面的示例中,我们用endsWith()方法来判断字符串str是否以'world!'、'World!'和'Hello'结尾,并输出相关结果。
总结
本文介绍了在JavaScript中判断字符串包含的几种常见方法,包括includes()、indexOf()、startsWith()和endsWith()。在实际开发中,根据具体需求选择合适的方法来判断字符串包含,可以很好地提高开发效率。
极客笔记