使用indexOf()方法:该方法返回指定字符串在原字符串中第一次出现的索引位置,如果找不到则返回-1。例如:
let str = "Hello, World!";
let searchTerm = "World";
let index = str.indexOf(searchTerm);
console.log(index); // 输出 7
使用search()方法:该方法返回指定字符串在原字符串中第一次出现的索引位置,如果找不到则返回-1。该方法支持使用正则表达式进行匹配。例如:
let str = "Hello, World!";
let searchTerm = /world/i; // 忽略大小写
let index = str.search(searchTerm);
console.log(index); // 输出 7
使用includes()方法:该方法返回一个布尔值,表示原字符串是否包含指定字符串。例如:
let str = "Hello, World!";
let searchTerm = "World";
let isFound = str.includes(searchTerm);
console.log(isFound); // 输出 true
使用match()方法:该方法以指定的正则表达式来检索字符串,并返回一个包含所有匹配的数组。例如:
let str = "Hello, World!";
let searchTerm = /world/i; // 忽略大小写
let matches = str.match(searchTerm);
console.log(matches); // 输出 ["World"]