JS中有多种方法可以判断字符串,其中最常用的是indexOf()方法、includes()方法、startsWith()方法和endsWith()方法。
indexOf()方法用于检索字符串中是否存在指定的字符,如果存在,则返回字符串中第一次出现的位置,如果不存在,则返回-1,使用方法如下:
var str = "Hello World";
var index = str.indexOf("World");
// index的值为6
includes()方法用于检测字符串是否包含指定的字符,如果存在,则返回true,如果不存在,则返回false,使用方法如下:
var str = "Hello World";
var result = str.includes("World");
// result的值为true
startsWith()方法用于检测字符串是否以指定的字符开头,如果是,则返回true,如果不是,则返回false,使用方法如下:
var str = "Hello World";
var result = str.startsWith("Hello");
// result的值为true
endsWith()方法用于检测字符串是否以指定的字符结尾,如果是,则返回true,如果不是,则返回false,使用方法如下:
var str = "Hello World";
var result = str.endsWith("World");
// result的值为true
以上就是JS中判断字符串的几种常用方法,通过这些方法可以快速检测字符串中是否存在指定的字符,从而实现字符串的判断。