js有一个字符串是否包含另一个字符串

JavaScript015

js有一个字符串是否包含另一个字符串,第1张

js 代码是支持很多String 类的方法的,建议你可以用indexOf 来判断一个字符串是否存在于另一个字符串中,示例:

判断aaa 是否存在于 123aaa456 中

'123aaa456'.indexOf('aaa')

如果返回值不等于-1 说明存在

在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')

}