您的位置:

JS判断字符串包含某个字符的方法

一、使用includes()函数

1、includes()函数是ES6中新增的字符串方法,用于判断一个字符串是否包含另一个字符串。该方法返回一个布尔值,如果包含则为true,不包含则为false。

2、includes()函数的语法如下:

str.includes(searchString[, position])

其中,searchString是要查找的字符串,必需。position是可选的,表示从字符串的哪个索引开始查找,默认值为0。

3、下面是一个示例代码:

const str = 'hello world'
console.log(str.includes('world')) // 输出 true

二、使用indexOf()函数

1、indexOf()函数同样是用于查找字符串中某个子字符串的位置,如果包含则返回该子串首次出现的位置,否则返回-1。

2、indexOf()函数的语法如下:

str.indexOf(searchValue[, fromIndex])

其中,searchValue是要查找的字符串,必需。fromIndex是可选的,表示从字符串的哪个索引开始查找。

3、下面是一个示例代码:

const str = 'hello world'
console.log(str.indexOf('world')) // 输出 6

三、使用正则表达式

1、在JS中也可以使用正则表达式来判断一个字符串是否包含某个字符。可以使用test()函数来测试一个字符串是否匹配某个模式,如果匹配则返回true,否则返回false。

2、下面是一个示例代码:

const str = 'hello world'
const pattern = /world/
console.log(pattern.test(str)) // 输出 true

四、使用字符串的match()方法

1、match()方法同样是用于查找字符串中的子字符串。该方法支持传入一个字符串或正则表达式,并返回一个数组,其中包含所有匹配的子串。

2、match()函数的语法如下:

str.match(regexp)

其中,regexp可以是一个字符串或一个正则表达式。

3、下面是一个示例代码:

const str = 'hello world'
const pattern = /world/
console.log(str.match(pattern)) // 输出 ["world"]

五、使用ES6的模板字符串

1、ES6的模板字符串中支持使用${}来引用变量。如果在${}中引用的字符串中包含搜索的字符,则说明该字符串包含该字符。

2、下面是一个示例代码:

const str = 'hello world'
const char = 'world'
if (str.includes(`${char}`)) {
  console.log('包含该字符')
} else {
  console.log('不包含该字符')
}

通过以上五个方法,我们可以在JS中方便地判断一个字符串是否包含某个字符或子串。