js判断字符串中是否包含某个字符

JavaScript0192

js判断字符串中是否包含某个字符,第1张

可以用js的indexOf,lastIndexOf函数进行判断。

这两个函数返回字符出现的位置,如果没有找到,就会返回"-1"。

也可以使用match,search方法,查找字符串当中是否存在某个字符。

在java中一般有两种方法较常用,分别是contains(String str)和indexOf(String str)。

其中contains返回值为boolean类型,true为有,false为没有;而indexOf实际上是查找一个字符串在另一个字符串的位置的一个方法,且以匹配好的第一个字符为准;所以该方法的返回值为int类型,其中 -1表示未找到,其余都是能找到意思。所以一般来讲,java中的判断方式如下:

String str = "abcde"

//第一种方法

if (str.contains("b")) {

    System.out.println("yes")

} else {

    System.out.println("no")

}

//第二种方法

if (str.indexOf("bc") >= 0) {

    System.out.println(str.indexOf("bc"))

    System.out.println("yes")

} else {

    System.out.println("no")

}

而在js中较为常见方法为indexOf(),返回值同java一样,为最常用的方法;随后,ES6又提供了三种新方法。includes(),返回布尔值,表示是否找到了参数字符串;startsWith(),返回布尔值,表示参数字符串是否在源字符串的头部;endsWith(),返回布尔值,表示参数字符串是否在源字符串的尾部。

var s = 'Hello world!'

if(s.indexOf('world')>=0){

    console.log('true')

}

if(s.includes('o')){

    console.log('true')

}

if(s.startsWith('Hello')){

    console.log('true')

}

if(s.endsWith('!')){

    console.log('true')

}