例如,有一个字符串str="Hello World",想判断它是否包含字符'o',可以使用indexOf()方法:
var str="Hello World"; var result=str.indexOf('o'); if(result!=-1){ console.log('字符串中包含字符o'); }else{ console.log('字符串中不包含字符o'); }
上面代码中,str.indexOf('o')的返回值为4,表示字符串str中包含字符'o',输出字符串中包含字符o。
还可以使用includes()方法来判断字符串中是否包含某个字符,如果字符串中包含指定的字符,则返回true,如果不包含,则返回false。
var str="Hello World"; var result=str.includes('o'); if(result){ console.log('字符串中包含字符o'); }else{ console.log('字符串中不包含字符o'); }
上面代码中,str.includes('o')的返回值为true,表示字符串str中包含字符'o',输出字符串中包含字符o。
JavaScript中可以使用indexOf()或includes()方法来判断字符串中是否包含某个字符。