判断某一字符中是否存在指定字符串

149 阅读1分钟

1、indexOf方法

"请找出只因在哪里".indexOf("只因") //返回值 3
"请找出只因在哪里".indexOf("鸡")   //返回值 -1

2、includes方法

"请找出只因在哪里".includes("只因") //返回值 true
"请找出只因在哪里".includes("鸡")   //返回值 false

3、search方法

"请找出只因在哪里".search("只因") //返回值 3
"请找出只因在哪里".search("鸡")   //返回值 -1

4、match方法(涉及正则表达式)

let str = "阿坤琨捆困"
let reg = RegExp(/坤/)
str.match(reg)
简写上述代码:
"阿坤琨捆困".match(RegExp(/坤/))  //返回值 ['坤', index: 1, input: '阿坤琨捆困', groups: undefined]
"阿坤琨捆困".match(RegExp(/蔡/)) //返回值 null

5、test方法(涉及正则表达式)

let str = "阿坤琨捆困"
let reg = RegExp(/坤/)
reg.test(str)
简写上述代码:
RegExp(/坤/).test("阿坤琨捆困") //返回值 true
RegExp(/蔡/).test("阿坤琨捆困") //返回值 false

6、exec方法(涉及正则表达式)

let str = "阿坤琨捆困"
let reg = RegExp(/坤/)
reg.exec(str)
简写上述代码:
RegExp(/坤/).exec("阿坤琨捆困") //返回值 ['坤', index: 1, input: '阿坤琨捆困', groups: undefined]
RegExp(/蔡/).exec("阿坤琨捆困") //返回值 null