JavaScript 中有很多方法可以判断字符串中是否包含指定内容,比如indexOf()方法、includes()方法、search()方法、match()方法和test()方法。
indexOf()方法用于判断字符串中是否包含指定字符,如果包含,则返回字符的索引位置,如果不包含,则返回-1。例如:
var str = "Hello world!";
console.log(str.indexOf('world')); // 6
console.log(str.indexOf('World')); // -1
可以看出,indexOf()方法区分大小写,如果要忽略大小写,可以使用toLowerCase()方法先将字符串转换为小写,再使用indexOf()方法。
includes()方法与indexOf()方法类似,也用于判断字符串中是否包含指定字符,不同的是,它返回的是布尔值,如果包含,则返回true,如果不包含,则返回false。例如:
var str = "Hello world!";
console.log(str.includes('world')); // true
console.log(str.includes('World')); // false
includes()方法也区分大小写,如果要忽略大小写,可以先将字符串转换为小写,再使用includes()方法。
search()方法用于搜索指定字符串在字符串中的位置,如果找到,则返回字符串的位置,如果没有找到,则返回-1。例如:
var str = "Hello world!";
console.log(str.search('world')); // 6
console.log(str.search('World')); // -1
search()方法也区分大小写,如果要忽略大小写,可以先将字符串转换为小写,再使用search()方法。
match()方法用于搜索字符串中的指定字符,如果找到,则返回一个数组,如果没有找到,则返回null。例如:
var str = "Hello world!";
console.log(str.match('world')); // ["world"]
console.log(str.match('World')); // null
match()方法也区分大小写,如果要忽略大小写,可以使用正则表达式,并将其设置为忽略大小写。
test()方法用于搜索字符串中的指定字符,如果找到,则返回true,如果没有找到,则返回false。例如:
var str = "Hello world!";
console.log(str.test('world')); // true
console.log(str.test('World')); // false
test()方法也区分大小写,如果要忽略大小写,可以使用正则表达式,并将其设置为忽略大小写。
JavaScript 中有多种方法可以判断字符串中是否包含指定内容,比如indexOf()方法、includes()方法、search()方法、match()方法和test()方法,它们的功能类似,但是返回的结果不同,具体使用哪种方法,取决于实际的需求。